C++多线程编程:undefined reference to `pthread_create‘ collect2: error: ld returned 1 exit statu (CMake编译)

作者需要用到多线程编程,找到的例程如下:
多线程编程

#include <iostream>
#include<thread>
#include<unistd.h>
using namespace std;
void sayHello()
{
    while(1)
    {
        sleep(1);
        cout<<endl<<"hello"<<endl;
    }

}
void sayWorld()
{
    while(1)
    {
        sleep(1);
         cout<<endl<<"world"<<endl;
    }
}
int main()
{
    thread threadHello(sayHello);
    thread threadWorld(sayWorld);
    threadHello.join();
    threadWorld.join();

   return 0;
}

拿到本地后发现编译不过,报错如下:

sys-01@ubuntu:~/pro_hw/thread_cpp/build$ make
[ 50%] Building CXX object CMakeFiles/main.dir/main.cpp.o
[100%] Linking CXX executable main
CMakeFiles/main.dir/main.cpp.o: In function `std::thread::thread<void (&)()>(void (&)())':
main.cpp:(.text._ZNSt6threadC2IRFvvEJEEEOT_DpOT0_[_ZNSt6threadC5IRFvvEJEEEOT_DpOT0_]+0x7d): undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
CMakeFiles/main.dir/build.make:96: recipe for target 'main' failed
make[2]: *** [main] Error 1
CMakeFiles/Makefile2:82: recipe for target 'CMakeFiles/main.dir/all' failed
make[1]: *** [CMakeFiles/main.dir/all] Error 2
Makefile:90: recipe for target 'all' failed
make: *** [all] Error 2

经过查找得知,这是因为thread不属于std标准库,所以需要额外链接。也就是需要修改CMakeLists.txt。修改后的CMake如下:

cmake_minimum_required(VERSION 2.6)
project(Test)

add_definitions(-std=c++11)
add_definitions(-w)

add_definitions(-pthread)//修改第一处
add_executable(main main.cpp)
target_link_libraries(main pthread)//修改第二处

总共修改了两处1.添加编译参数 2.链接库文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值