[转]c++使用thread类时编译出错,对‘pthread_create’未定义的引用

转载地址:https://blog.csdn.net/wuhui20091515/article/details/52531202

例子1

#include <iostream>

#include <thread>

using namespce std;

void hello()

{

      cout << "hello concurent world!";

}

int main (int argc, char * argv[])

{

     thread t(hello);

     t.join();

    return 0;

}

这个小例子直接用make编译是无法通过的。会报错

/tmp/ccYB66pt.o:在函数‘std::thread::thread<void (&)()>(void (&)())’中:
1-1.cpp:(.text._ZNSt6threadC2IRFvvEJEEEOT_DpOT0_[_ZNSt6threadC5IRFvvEJEEEOT_DpOT0_]+0x21):对‘pthread_create’未定义的引用
collect2: 错误:ld 返回 1
<builtin>: recipe for target '1-1' failed
make: *** [1-1] Error 1

解决方法是在编译的时候加上-lpthread参数。这个类用到posix实现的线程了。

g++ -o test test.cpp -lpthread

./test

结果输出 hello concurent world!

猜你喜欢

转载自www.cnblogs.com/qiuheng/p/9273814.html