描述
在linux下编译c++程序时报错:
/usr/bin/ld: /tmp/ccjbNBGi.o: in function __static_initialization_and_destruction_0(int, int)‘:
/usr/include/c++/9/iostream:74: undefined reference to std::ios_base::Init::Init()
/usr/bin/ld: /usr/include/c++/9/iostream:74: undefined reference to std::ios_base::Init::~Init()’
collect2: error: ld returned 1 exit status
Build finished with error(s).
原因
使用的是gcc编译器,gcc是c语言编译器,默认链接的库是libc.so,要使其链接到c++的库libstdc++.so。
解决方法
方法1 在命令后添加-lstdc++
gcc helloworld.cpp -lstdc++
方法2 在vscode的tasks.json中添加参数
若使用vscode作为IDE,可在tasks.json的“args”中添加链接库参数:
"-l",
"stdc++"
方法3 将编译器改为g++
无论是.c后缀还是.cpp后缀,g++都认为是c++程序,g++可以自动连接c++标准库。
g++ helloworld.cpp -o HelloWorld
或在vscode的tasks.json中将command改为g++的路径。
"command": "/usr/bin/g++",