When g Static Links Pthread, Causing Segmentation Fault: Explanation and Solution
Problem:
When compiling a C program with g and the -pthread flag for linking against the pthread library, but statically (-static), the program encounters a Segmentation Fault.
Explanation:
Weak Symbols:
Dynamic Linking vs. Static Linking:
Incomplete Link Resolution:
Solution:
To force the linker to look at all symbols from the pthread library in a statically linked program, use:
g++ -o one one.cpp -Wall -std=c++11 -O3 -static -pthread \ -Wl,--whole-archive -lpthread -Wl,--no-whole-archive
Additional Notes:
WL_WHOLE_ARCHIVE_HACK="-Wl,--whole-archive" WL_NO_WHOLE_ARCHIVE_HACK="-Wl,--no-whole-archive" AC_SUBST(WL_WHOLE_ARCHIVE_HACK) AC_SUBST(WL_NO_WHOLE_ARCHIVE_HACK) mytarget_LDADD = @WL_WHOLE_ARCHIVE_HACK@ -lpthread @WL_NO_WHOLE_ARCHIVE_HACK@
The above is the detailed content of Why Does My C Program With Static Linking and Pthreads Result in a Segmentation Fault?. For more information, please follow other related articles on the PHP Chinese website!