GCC和Clang无法编译C++代码

GCC和Clang无法编译C++代码

尝试运行命令gcc code.cpp -o runthis

但是它给了我这种格式的错误:

/usr/bin/ld: /tmp/cco6J3Vh.o: warning: relocation against `_ZSt4cout' in read-only section `.text'
/usr/bin/ld: /tmp/cco6J3Vh.o: in function `main':
code.cpp:(.text+0x28): undefined reference to `std::cout'
/usr/bin/ld: code.cpp:(.text+0x30): 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: code.cpp:(.text+0x3e): undefined reference to `std::cin'
/usr/bin/ld: code.cpp:(.text+0x46): undefined reference to `std::istream::operator>>(int&)'
/usr/bin/ld: code.cpp:(.text+0x9e): undefined reference to `std::cout'
/usr/bin/ld: code.cpp:(.text+0xa6): undefined reference to `std::ostream::operator<<(int)'
/usr/bin/ld: code.cpp:(.text+0xbb): 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: code.cpp:(.text+0xc9): undefined reference to `std::cout'
/usr/bin/ld: code.cpp:(.text+0xd1): undefined reference to `std::ostream::operator<<(int)'
/usr/bin/ld: code.cpp:(.text+0xe6): 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: /tmp/cco6J3Vh.o: in function `__static_initialization_and_destruction_0(int, int)':
code.cpp:(.text+0x12d): undefined reference to `std::ios_base::Init::Init()'
/usr/bin/ld: code.cpp:(.text+0x148): 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

网上查了一下,好像是链接器的问题。我在 Arch Linux 上。 Clang 给了我与 gcc 相同的错误,但是我可以使用 c++ 进行编译。任何帮助表示赞赏

答案1

您正在尝试使用 C 编译器编译 C++。使用g++(或clang++),即 C++ 编译器,而不是 C 编译器gcc(或clang,分别)。这不是 GCC 或 clang 的问题 – 这是针对您的语言使用了错误的编译器!

您收到的错误是因为 C 编译器即使正确识别 C++,也不会尝试与标准 C++ 库链接。

相关内容