Compiling multithread code with g++
The answer was provided by a kind member of SO C++ chat.
It looks like this behaviour is caused by a bug in gcc.
The workaround provided in the last comment of that bug discussion does work and solves the issue:
-Wl,--no-as-needed
Adding -lpthread
fixed the identical problem for me:
g++ -std=c++11 foo.cpp -lpthread -o foo
I have slightly more advanced version (4.8.4 instead of 4.8.1), and I tested all three answers above. In fact:
-pthread
alone works:
g++ -std=c++11 -o main -pthread main.cpp
-Wl,--no-as-needed
alone does not work.
-lpthread
alone does not work.
-Wl,--no-as-needed
and -lpthread
together work:
g++ -std=c++11 -o main -Wl,--no-as-needed main.cpp -lpthread
My version is "g++ (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4".