尝试运行命令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++ 进行编译。任何帮助表示赞赏
您正在尝试使用 C 编译器编译 C++。使用
g++
(或clang++
),它是一个 C++ 编译器,而不是 C 编译器gcc
(或clang
,分别)。这不是 GCC 或 clang 的问题——这是为您的语言使用了错误的编译器!您遇到的错误是因为 C 编译器即使正确识别 C++,也不会尝试与标准 C++ 库链接。