Home  >  Article  >  Backend Development  >  Here are a few question-based titles that fit the content of your article: * Why does using -static with -pthread for C compilation cause Segmentation Faults? * How to resolve Segmentation Faults w

Here are a few question-based titles that fit the content of your article: * Why does using -static with -pthread for C compilation cause Segmentation Faults? * How to resolve Segmentation Faults w

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 21:25:02965browse

Here are a few question-based titles that fit the content of your article:

* Why does using -static with -pthread for C   compilation cause Segmentation Faults?
* How to resolve Segmentation Faults when statically linking pthread in C  ?
* Static vs. Dyn

When compiling C code with g and the -pthread flag to enable multithreading, using -static to link statically against the pthread library can lead to a Segmentation fault. This occurs because the statically linked pthread library lacks the necessary weak symbols, including pthread_mutex_lock(), which are defined in the glibc library.

To resolve this issue, ensure that the executable is dynamically linked against pthread by passing the -lpthread flag to the linker. This will force the linker to include the required weak symbols from the shared library version of pthread.

Alternatively, if static linking is required, use the following command to compile the program:

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

The -Wl,--whole-archive option forces the linker to include all object files from the pthread library, ensuring that the required weak symbols are included. The -Wl,--no-whole-archive option turns off this behavior for subsequent archive files.

The above is the detailed content of Here are a few question-based titles that fit the content of your article: * Why does using -static with -pthread for C compilation cause Segmentation Faults? * How to resolve Segmentation Faults w. 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