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++ をコンパイルしようとしています。Cコンパイラ(g++または) の代わりに、C++ コンパイラである (または ) を使用してください。これは GCC や clang の問題ではなく、言語に適さないコンパイラを使用していることが原因です。clang++gccclang

発生するエラーは、C コンパイラが C++ を正しく認識しても、標準 C++ ライブラリとのリンクを試行しないために発生します。

関連情報