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 !