Home >Backend Development >C++ >How to Correctly Link std::thread in GCC with pthread?

How to Correctly Link std::thread in GCC with pthread?

Barbara Streisand
Barbara StreisandOriginal
2024-12-02 20:08:11303browse

How to Correctly Link std::thread in GCC with pthread?

Correct Link Options for std::thread in GCC

In GCC under Linux, std::thread utilizes pthread for its implementation. To successfully use std::thread, it's crucial to specify the appropriate link options during compilation.

Compilation Issue and Solution

The provided example code encounters an error because the necessary pthread library is not linked. To fix this issue, add the -pthread linker flag after the source file during compilation:

$ g++ -std=c++0x test.cpp -pthread

Order of Options

Note that linker options should be placed after the source files during compilation. This is because the compiler first processes the source code, and then the linker finalizes the binary by resolving any necessary dependencies.

Example

The corrected compilation command would be:

$ g++ -std=c++0x test.cpp -pthread

By following this guidance, you can correctly link your std::thread usage in GCC under Linux, allowing your multithreaded code to execute as intended.

The above is the detailed content of How to Correctly Link std::thread in GCC with pthread?. 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