为什么使用 gcc 编译简单的 C++ 程序会出现“未定义引用”错误?

为什么使用 gcc 编译简单的 C++ 程序会出现“未定义引用”错误?

我尝试在 Ubuntu 中编译 c++。我在 Gedit 中编写代码,这是一个简单的 hello world 项目。我进入终端运行它,然后gcc helloworld.cc弹出以下消息:

/tmp/ccy83619.o: In function `main':
helloworld.cc:(.text+0xa): undefined reference to `std::cout'
helloworld.cc:(.text+0xf): 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*)'
/tmp/ccy83619.o: In function `__static_initialization_and_destruction_0(int, int)':
helloworld.cc:(.text+0x3d): undefined reference to `std::ios_base::Init::Init()'
helloworld.cc:(.text+0x4c): undefined reference to `std::ios_base::Init::~Init()'
collect2: error: ld returned 1 exit status

这是什么意思?我下一步该怎么做?

答案1

C++ 程序需要与 C++ 标准库链接。尽管你可以手动链接标准库,即gcc -o hello hello.cpp -lstdc++,通常不这样做。相反,您应该使用g++代替gcc,它会libstdc++自动链接。

例如给定

$ cat hello.cpp
#include <iostream>

int main(void) { std::cout << "Hello world" << std::endl; return 0; }

然后

$ gcc -o hello hello.cpp
/tmp/ccty9cjF.o: In function `main':
hello.cpp:(.text+0xa): undefined reference to `std::cout'
hello.cpp:(.text+0xf): 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*)'
hello.cpp:(.text+0x14): 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> >&)'
hello.cpp:(.text+0x1c): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))'
/tmp/ccty9cjF.o: In function `__static_initialization_and_destruction_0(int, int)':
hello.cpp:(.text+0x4a): undefined reference to `std::ios_base::Init::Init()'
hello.cpp:(.text+0x59): undefined reference to `std::ios_base::Init::~Init()'
collect2: error: ld returned 1 exit status

然而

g++ -o hello hello.cpp
$ ./hello
Hello world

相关内容