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

온라인으로 확인해 보니 링커 문제인 것 같습니다. 저는 아치 리눅스를 사용하고 있습니다. Clang에서는 gcc와 동일한 오류가 발생하지만 C++를 사용하여 컴파일할 수 있습니다. 도움을 주시면 감사하겠습니다.

답변1

C 컴파일러로 C++를 컴파일하려고 합니다. C 컴파일러 (또는 각각) 대신 C++ 컴파일러인 g++( 또는 )을 사용하십시오 . 이것은 GCC나 clang의 문제가 아닙니다. 이는 귀하의 언어에 잘못된 컴파일러를 사용하고 있기 때문입니다!clang++gccclang

발생하는 오류는 C 컴파일러가 C++를 올바르게 인식하더라도 표준 C++ 라이브러리와 연결을 시도하지 않기 때문에 발생합니다.

관련 정보