用我们的决心、信心和毅力来培植我们的生命之花🍀|

3的4次方

园龄:2年1个月粉丝:5关注:89

2023-01-10 21:21阅读: 1481评论: 0推荐: 0

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 中国大陆许可协议进行许可。

posted @   3的4次方  阅读(1481)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起