Home  >  Article  >  Backend Development  >  Why does statically linking pthread with g cause a segmentation fault, and how can I fix it?

Why does statically linking pthread with g cause a segmentation fault, and how can I fix it?

DDD
DDDOriginal
2024-10-25 20:05:29736browse

Why does statically linking pthread with g   cause a segmentation fault, and how can I fix it?

Why does g cause a segmentation fault when statically linking pthread?

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.

Weak Symbols

ELF files (used in Unix) differentiate between strong and weak symbols:

  • Strong: Can override weak symbols with the same name.
  • Weak: Can be overridden by strong symbols, but not by other weak symbols.

pthread 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.

Use of -Wl,--whole-archive and -Wl,--no-whole-archive

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!

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