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
Release: 2024-12-02 20:08:11
Original
348 people have browsed it

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
Copy after login
Copy after login

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
Copy after login
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template