Home >Backend Development >C++ >Why Does My C `std::thread` Code Fail to Link on Linux with GCC, and How Can I Fix It?

Why Does My C `std::thread` Code Fail to Link on Linux with GCC, and How Can I Fix It?

Linda Hamilton
Linda HamiltonOriginal
2024-11-29 07:08:09241browse

Why Does My C   `std::thread` Code Fail to Link on Linux with GCC, and How Can I Fix It?

Resolving Linking Issues when using std::thread with GCC on Linux

In the realm of multithreading with C , the C Standard Library provides the std::thread class. When attempting to utilize std::thread with GCC on a Linux system, the following error might arise:

terminate called after throwing an instance of 'std::system_error'
what(): Operation not permitted 
Aborted

Cause:

This error indicates that proper linking options have not been specified for the compiler to resolve dependencies related to std::thread. Specifically, on Linux, the pthread library is involved in the implementation of std::thread.

Solution:

To address this issue, the -pthread compiler option must be employed. This option instructs the compiler to link the program against the pthread library. Here's how to correctly compile the code with the appropriate linking option:

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

Linking Option Placement:

It's crucial to note that the -pthread option should be listed after the source file(.cpp) when compiling. This ensures that the compiler correctly resolves the dependencies.

Revised Command:

After adding the -pthread option, the revised compilation command will appear as:

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

By incorporating the -pthread option, the code will successfully compile and execute, allowing std::thread to function as intended for multithreading in your Linux environment.

The above is the detailed content of Why Does My C `std::thread` Code Fail to Link on Linux with GCC, 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