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 !