Linux 下使用GCC/G++编译C++程序
Linux 下使用GCC/G++编译C++程序
例程:
/* hello.cpp */ #include <iostream> using namespace std; int main() { cout << "hello cpp"<<endl; return 0; }
使用GCC编译器
直接使用 gcc 编译:
gcc hello.cpp
编译失败,输出一堆信息:
/usr/bin/ld: /tmp/ccQc3RFB.o: warning: relocation against `_ZSt4cout' in read-only section `.text' /usr/bin/ld: /tmp/ccQc3RFB.o: in function `main': hello.cpp:(.text+0x15): undefined reference to `std::cout' /usr/bin/ld: hello.cpp:(.text+0x1d): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)' /usr/bin/ld: hello.cpp:(.text+0x24): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)' /usr/bin/ld: hello.cpp:(.text+0x2f): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))' /usr/bin/ld: /tmp/ccQc3RFB.o: in function `__static_initialization_and_destruction_0(int, int)': hello.cpp:(.text+0x66): undefined reference to `std::ios_base::Init::Init()' /usr/bin/ld: hello.cpp:(.text+0x81): undefined reference to `std::ios_base::Init::~Init()' /usr/bin/ld: warning: creating DT_TEXTREL in a PIE collect2: error: ld returned 1 exit status
正确做法是需要手动加选项连接到C++标准库:
gcc hello.cpp -lstdc++
成功编译。
使用G++编译器
- g++将gcc默认语言设为C++的一个特殊版本
- 链接时它自动用 C++ 标准库而不用C标准库
- 通过遵循源码的命名规范并指定对应库的名字
直接使用g++命令
g++ hello.cpp
成功编译。
本文作者:3的4次方
本文链接:https://www.cnblogs.com/3to4/p/17041427.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步