2

CppCon 2015: Detlef Vollmann “Executors for C++ - A Long Story ..." starts off with this example:

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

C++ reference shows std::async is in <future> and std::cout is in <iostream>. What is missing to make the build work?

$ 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)
CW Holeman II
  • 4,661
  • 7
  • 41
  • 72
  • Possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Alan Stokes Jan 15 '16 at 23:47

2 Answers2

10

You need to compile with -pthread so that the linker lets you make use of async/future/thread functionality.

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
pacevedo
  • 116
  • 3
  • @Joshua In `GCC/clang` `-lpthread` is deprecated in favour of `-pthread`. – Galik Jan 16 '16 at 00:02
  • @pacevedo, where would that be documented that one could find it w/o first knowing the answer, from undefined reference to `pthread_create'? – CW Holeman II Jan 16 '16 at 01:03
0

For many libraries, you have to include a reference to the library while linking. For <future>, I believe it's --pthread.

So try, clang++ --std=c++14 cppcon15.cpp --pthread.

Nathan
  • 505
  • 2
  • 8