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

成功编译。

posted @ 2023-01-10 21:21  3的4次方  阅读(1334)  评论(0编辑  收藏  举报