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

Tzi*_*kos 4 compiling 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
Run Code Online (Sandbox Code Playgroud)

这是什么意思,我该往哪里去?

ste*_*ver 8

C++ 程序需要与 C++ 标准库链接。虽然您可以手动链接标准库 ie 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; }
Run Code Online (Sandbox Code Playgroud)

然后

$ 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
Run Code Online (Sandbox Code Playgroud)

然而

g++ -o hello hello.cpp
$ ./hello
Hello world
Run Code Online (Sandbox Code Playgroud)