Подобное уже обсуждалось в системе отслеживания ошибок GCC. Как оказалось, это связано с тем, что libpthread не рассчитана на статическую компоновку:
При $ g++-4.7 -Wl,-M -v -static -pthread -std=c++0x -o thread thread.cc
libpthread компонуется без проблем.
Проведя небольшое расследование, я выяснил, что /usr/include/c++/4.7.0/x86_64-linux-gnu/bits/gthr-posix.h
объявляет всё как __attribute__((weakref))
даже при статической компоновке, из-за чего все символы __gthread_*
обращаются в нулевые. Дополнительная информация может быть найдена по ссылке http://gcc.gnu.org/ml/gcc/2005-10/msg00235.html
Следующие флаги компиляции должны помочь:
$ g++ -D_GLIBCXX_GTHREAD_USE_WEAK=0 -static -pthread -std=c++0x -o thread thread.cc
$ ./thread
pthread_create works
std::thread works
Однако, если заменить join()
на detach()
, программа снова падает, на этот раз из-за нулевой ссылки на std::thread::detach
:
Program received signal SIGSEGV, Segmentation fault.
0x0000000000000000 in ?? ()
(gdb) bt
#0 0x0000000000000000 in ?? ()
#1 0x0000000000439785 in std::thread::detach() ()
#2 0x0000000000401f52 in main ()
$ g++-4.7 -Wl,-M -v -static -pthread -std=c++0x -o thread thread.cc
shows all of libpthread being linked.
With a bit more digging I traced the problem to /usr/include/c++/4.7.0/x86_64-linux-gnu/bits/gthr-posix.h
declaring all of its symbols with __attribute__((weakref))
even when linking statically. Which caused the __gthread_*
symbols to resolve to zero. I found this for some background info http://gcc.gnu.org/ml/gcc/2005-10/msg00235.html
This change made my example work:
$ g++ -D_GLIBCXX_GTHREAD_USE_WEAK=0 -static -pthread -std=c++0x -o thread thread.cc
$ ./thread
pthread_create works
std::thread works
However, if I change the code to call std::thread::detach
instead of join
, then it crashes again with std::thread::detach
being resolved to zero.
Program received signal SIGSEGV, Segmentation fault.
0x0000000000000000 in ?? ()
(gdb) bt
#0 0x0000000000000000 in ?? ()
#1 0x0000000000439785 in std::thread::detach() ()
#2 0x0000000000401f52 in main ()
В связи с этим на англоязычном StackOverflow рекомендуют включить флаг компиляции -Wl,--whole-archive
, либо перечислить все необходимые библиотеки вручную, узнав предварительно список зависимостей через nm
.
А вообще:
Даже не думайте о статической компоновке. Разработчики glibc это не любят и не поддерживают. И однажды они начнут усложнять подобную практику с каждым релизом.
Do not even think about static linking. The glibc developers do not like it, they do not care about supporting it, and they somehow manage to break it a little harder with every release.