g++编译包含“pthread.h”头文件报错:对‘pthread_create’未定义的引用

1.在cpp程序代码中包含了“pthread.h”头文件,直接编译会报类似“对'pthread_create'未定义”的错误。

Eg:有文件thread.cpp,里面包含使用了“pthread.h”头文件和函数

编译:g++ -o thread.out thread.cpp

报错:在函数'main'中:

thread.cpp:(.text+0x5c): 对'pthread_create'未定义的引用

thread.cpp:(.text+0x87): 对'pthread_join'未定义的引用

collect2:错误:ld返回1

修改编译命令:g++ -pthread -c -o thread.out thread.cpp

编译通过,生成了thread.out文件,运行也没有错误。

 

2.假如有多个文件,为了方便需要用Makefile来编写编译代码。但其中有一个中间文件包含使用了“pthread.h”头文件和函数,则需要在最后综合生成可执行文件时添加"-lpthread"。

Eg:hello.h ,hello.cpp,thread-t.h,thread-t.cpp,main.cpp,生成目标一个:main.out

**hello.h:

extern void hello();

 

**hello.cpp:

#include "hello.h"

#include <iostream>

void hello()

{

    std::cout<<"hello world !"<<std::endl;

}

 

**thread-t.h:

extern void usethread();

 

**thread-t.cpp:

#include "thread-t.h"

#include <thread>

#include "hello.h"

#include <iostream>

void usethread()

{

    std::thread t(hello);

    t.join();

}

 

**main.cpp:

#include "thread-t.h"

int main()

{

    usethread();

    return 0;

}

 

Makefile:

main.out:main.o thread-t.o hello.o

    g++ -lpthread -o main.out main.o thread-t.o hello.o #因为最后目标包含了“thread-t.h",所以还需要在编译的时候添加”-lpthread“

main.o:main.cpp 

    g++ -c -o main.o main.cpp

thread-t.o:thread-t.cpp

    g++ -lpthread -c -o thread-t.o thread-t.cpp 

hello.o:hello.cpp

    g++ -c -o hello.o hello.cpp

 

.PHONY:clean

clean:

    rm -r *.o *.out

***

make 

./main.out

hello world !

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值