Home  >  Article  >  Backend Development  >  Why Does My C Program With Static Linking and Pthreads Result in a Segmentation Fault?

Why Does My C Program With Static Linking and Pthreads Result in a Segmentation Fault?

DDD
DDDOriginal
2024-10-26 11:14:02966browse

Why Does My C   Program With Static Linking and Pthreads Result in a Segmentation Fault?

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:

  1. Weak Symbols:

    • pthread and libstdc use weak symbols for certain functions, such as pthread_mutex_lock().
    • Weak symbols can be replaced by strong symbols during linking.
  2. Dynamic Linking vs. Static Linking:

    • In dynamic linking, weak symbols are resolved from shared libraries.
    • In static linking, the linker stops at the first symbol (including weak ones) and doesn't search for strong symbols.
  3. Incomplete Link Resolution:

    • When using -static, the linker doesn't consider all symbols from the pthread library, as it encounters a weak symbol first.
    • Consequently, the strong symbol for pthread_mutex_lock() is not used.

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
  • -Wl,--whole-archive: Includes all object files in the specified archive.
  • -lpthread: Links against the pthread library.
  • -Wl,--no-whole-archive: Disables the whole-archive option for subsequent archives.

Additional Notes:

  • Some systems may require additional flags, such as -lrt for librt.
  • If using Autotools, define the flags in configure.ac and substitute them in Makefile.am. For example:
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!

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