The Solution:
To resolve this issue, use the following command:
g++ -o one one.cpp -Wall -std=c++11 -O3 -static -lrt -pthread \ -Wl,--whole-archive -lpthread -Wl,--no-whole-archive
Understanding the Problem:
Statically linking to pthread requires a specific approach due to the use of weak symbols.
ELF files (used in Unix) differentiate between strong and weak symbols:
GLIBC and pthread use weak symbols for thread-safety features. The weak symbol versions are defined in the static libraries, while the strong symbol versions are defined in the dynamic libraries. When dynamic linking, the strong symbols are used, but when static linking, the weak symbols must be replaced with the strong versions.
When statically linking, the linker looks at the first symbol in an archive and stops searching. The -Wl,--whole-archive flag forces the linker to look at all symbols in the archive, including the weak symbols. The -Wl,--no-whole-archive flag turns off this option for subsequent archives.
By using these flags, you ensure that the strong symbol versions of the pthread functions are included in the executable, resolving the segmentation fault issue caused by weak symbols.
The above is the detailed content of Why does statically linking pthread with g cause a segmentation fault, and how can I fix it?. For more information, please follow other related articles on the PHP Chinese website!