Computer >> 컴퓨터 >  >> 프로그래밍 >> C++

GCC로 C++ 프로그램 컴파일하는 방법 완벽 가이드

이 글에서는 GCC(GNU C Compiler)를 사용하여 C++ 프로그램을 컴파일하는 방법을 알아보겠습니다. 다음과 같은 간단한 C++ 프로그램을 컴파일한다고 가정해 보겠습니다.

예제 코드

#include<iostream>
using namespace std;
main() {
   cout << "Hello World. This is C++ program" << endl;
}

만약 이것이 C 프로그램이라면, 아래와 같이 GCC로 간단히 컴파일할 수 있습니다.

gcc test.c

그러나 같은 방식으로 C++ 파일 이름을 넣으면 오류가 발생할 수 있습니다.

gcc test.cpp

오류 출력 결과

/tmp/ccf1KGDi.o: In function `main':
1325.test.cpp:(.text+0xe): undefined reference to `std::cout'
1325.test.cpp:(.text+0x13): 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*)'
1325.test.cpp:(.text+0x1d): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, 
std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
1325.test.cpp:(.text+0x28): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))'
/tmp/ccf1KGDi.o: In function `__static_initialization_and_destruction_0(int, int)':
1325.test.cpp:(.text+0x58): undefined reference to `std::ios_base::Init::Init()'
1325.test.cpp:(.text+0x6d): undefined reference to `std::ios_base::Init::~Init()'
collect2: error: ld returned 1 exit status
$

왜 이런 오류가 발생할까요?

여기서 주목해야 할 점은 이 오류가 컴파일 오류가 아니라 링킹(linking) 오류라는 것입니다. GCC는 기본적으로 C 표준 라이브러리만 연결하기 때문에, C++ 표준 라이브러리(libstdc++)에 정의된 std::cout, std::endl 같은 심볼들을 찾지 못해 발생하는 문제입니다.

해결 방법: -lstdc++ 옵션 사용

올바른 링커 라이브러리를 추가하려면 -lstdc++ 옵션을 사용하면 됩니다.

gcc test.cpp -lstdc++

정상 실행 결과

$ ./a.out
Hello World. This is C++ program
$

추가 팁

C++ 프로그램을 컴파일할 때는 g++ 명령어를 사용하는 것이 더 일반적입니다. g++은 C++ 컴파일에 필요한 라이브러리를 자동으로 연결해 주기 때문에 별도의 옵션 없이도 편리하게 사용할 수 있습니다.

g++ test.cpp

또한, 최신 C++ 표준(예: C++17)을 사용하려면 -std=c++17 옵션을 함께 지정하는 것이 좋습니다.