C++

GCC 和 Clang 無法編譯 C++ 程式碼

  • November 2, 2021

嘗試執行命令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++ 庫連結。

引用自:https://unix.stackexchange.com/questions/675828