Home >Backend Development >C++ >Why does my C program using `pthread` crash with a \'Segmentation fault\' when statically linked but works fine when dynamically linked?

Why does my C program using `pthread` crash with a \'Segmentation fault\' when statically linked but works fine when dynamically linked?

Linda Hamilton
Linda HamiltonOriginal
2024-11-02 00:46:02423browse

Why does my C   program using `pthread` crash with a

When g static link pthread, cause Segmentation fault, why?

This C program, when dynamically linked using -pthread -o one one.cpp -Wall -std=c 11 -O3, runs without any issues. However, when statically linked using -pthread -o one one.cpp -Wall -std=c 11 -O3 -static, it crashes with a "Segmentation fault".

Understanding the Issue

When using -pthread, the compiler automatically links against the pthread library. However, when statically linking, you need to explicitly specify -lpthread to include the pthread library.

Weak Symbols

In Unix, the ELF file format uses the concept of weak symbols, which can be overridden by strong symbols during linking. Glibc and pthread use weak symbols for functions that can be optionally replaced with optimized versions.

In this case, glibc provides weak symbols for synchronization functions like __pthread_mutex_lock. When pthread is linked dynamically, the weak symbols are replaced with strong symbols from pthread.

Static Linking and Weak Symbols

During static linking, the linker will stop at the first symbol it finds, even if it is a weak symbol. To include all symbols from the pthread library, you need to use the Wl,--whole-archive option, which forces the linker to include every object file from the archive.

Solution

To resolve the issue, use the following linking command:

g++ -o one one.cpp -Wall -std=c++11 -O3 -static -pthread \
    -Wl,--whole-archive -lpthread -Wl,--no-whole-archive

Appendix: Autotools Workaround

If using Autotools as a build system, the following workaround is required, as Automake does not allow options in LDADD:

In configure.ac:

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)

In Makefile.am:

mytarget_LDADD = @WL_WHOLE_ARCHIVE_HACK@ -lpthread @WL_NO_WHOLE_ARCHIVE_HACK@

The above is the detailed content of Why does my C program using `pthread` crash with a \'Segmentation fault\' when statically linked but works fine when dynamically linked?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn