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++ 程式庫連結。

相關內容