问题, 过去的正确答案,现在已经不行了
使用make编译c++文件报错。
/usr/bin/ld: build/obj/test.o: in function `main':
test.cpp:(.text+0x5ea): undefined reference to `pthread_create'
编译环境ubuntu19.04
gcc (Ubuntu 9.2.1-9ubuntu2) 9.2.1 20191008
g++ (Ubuntu 9.2.1-9ubuntu2) 9.2.1 20191008
众多网上答案,比如 https://blog.csdn.net/Desmend__/article/details/88754133
就是在编译选项中添加一个-lpthread
于是makefile添加“-lpthread"之后,如下所示
CXX:=g++
CXXFLAGS := -Wall -g -lpthread
# 省略许多
$(BUILD_DIR)/%: $(SRC_DIR)/%.cpp
@echo + G++ $@
@mkdir -p $(BUILD_DIR)
@echo "$(CXX) $(CXXFLAGS) -o $@ $<"
@$(CXX) $(CXXFLAGS) -o $@ $<
可以看到 CXXFLAGS大部分时间是被放到编译命令的中间的。
编译时的最终命令如下
g++ -Wall -g -lpthread -o build/test src/test.cpp
但是依然报错: undefined reference to `pthread_create’
解决办法
- -lpthread 与源文件放在一起
https://stackoverflow.com/questions/1662909/undefined-reference-to-pthread-create-in-linux
g++ -Wall -g -o build/test src/test.cpp -lpthread
- 使用-pthread进行连接
https://stackoverflow.com/questions/8264701/gcc-lpthread-not-working
g++ -Wall -pthread -g -o build/test src/test.cpp
具引用说,-lpthread连接的仅仅是是libpthread, 但是-pthread连接的是libpthread和其他很多东西。
总结
网上很多文章其实没有,只是需要主要-lpthread的添加位置,但是在makefile中,我们往往不直接添加-lpthread所以无法直接决定其添加在什么地方, 所以使用“-pthread”更好。