std :: async([](){std :: cout<<" Hello&#34 ;;})构建错误

时间:2016-01-15 23:43:05

标签: c++ build

CppCon 2015: Detlef Vollmann “Executors for C++ - A Long Story ..."从这个例子开始:

std::async([](){ std::cout << "Hello "; });
std::async([](){ std::cout << "World!\n"; });

C++ reference显示std::async位于<future>std::cout位于<iostream>。缺少什么使构建工作?

$ cat >hw.cpp <<EOF
> #include <iostream>
> int main(){
>     std::cout << "Hello World!\n";
> }
> EOF
$ clang++ -std=c++14 hw.cpp
$ ./a.out
Hello World!
$ cat >cppcon15.cpp <<EOF
> #include <future>
> #include <iostream>
> int main(){
>     std::async([](){ std::cout << "Hello "; });
>     std::async([](){ std::cout << "World!\n"; });
> }
> EOF
$ clang++ -std=c++14 cppcon15.cpp
/tmp/cppcon15-4f0a58.o: In function `std::thread::thread<std::__future_base::_Async_state_impl<std::_Bind_simple<main::$_1 ()>, void>::_Async_state_impl(std::_Bind_simple<main::$_1 ()>&&)::{lambda()#1}>(std::__future_base::_Async_state_impl<std::_Bind_simple<main::$_1 ()>, void>::_Async_state_impl(std::_Bind_simple<main::$_1 ()>&&)::{lambda()#1}&&)':
cppcon15.cpp:(.text+0x2cf6): undefined reference to `pthread_create'
/tmp/cppcon15-4f0a58.o: In function `std::thread::thread<std::__future_base::_Async_state_impl<std::_Bind_simple<main::$_0 ()>, void>::_Async_state_impl(std::_Bind_simple<main::$_0 ()>&&)::{lambda()#1}>(std::__future_base::_Async_state_impl<std::_Bind_simple<main::$_0 ()>, void>::_Async_state_impl(std::_Bind_simple<main::$_0 ()>&&)::{lambda()#1}&&)':
cppcon15.cpp:(.text+0x6bb6): undefined reference to `pthread_create'
clang: error: linker command failed with exit code 1 (use -v to see invocation)

2 个答案:

答案 0 :(得分:10)

您需要使用-pthread进行编译,以便链接器允许您使用异步/ future / thread功能。

答案 1 :(得分:0)

对于许多库,您必须在链接时包含对库的引用。 对于<future>,我相信--pthread

所以试试,clang++ --std=c++14 cppcon15.cpp --pthread