본문 바로가기

Study/C++

[Error]undefined reference to ~ 해결법

 

vscode로 코딩하고있었는데 이런 에러가 떴다.

이 에러가 뜨는 이유는 링커가 저 `TestClass()`의 위치를 못 찾았기 때문이다.

 

 

일단 이것부터 확인하자.

 

- 메소드를 구현했는가? .h에 선언만 해 놓고 .cpp에 구현은 아직 안 한게 아닌가?

- .cpp에 scope를 잘 지정했는가? void ClassName::method(){}이렇게 namespace를 잘 지정해줬는가?

 

위 조건을 지키면 웬만하면 해결된다. 만약 해결되지 않는다면 문법 오류가 아니고 링커 오류다.

링커 오류가 났을 때 해결법은 두 가지다. 1. 생성자 구현을 헤더 파일안에서 inline으로 해주거나, 2. g++로 컴파일할때 링크를 건드리거나.

 

 

1. 헤더 안에서 구현하기

간단한 방법이다. 헤더에서 구현해버리자. 대신 이렇게 하면 cpp파일에서 작성한 부분은 무시된다.

/** TestClass.h **/
#include <iostream>
class TestClass
{
    public:
        int x;
        TestClass(){x=10; std::cout << x;}; //헤더에서 구현
};



/** TestClass.cpp **/
#include "testClass.h"
TestClass::TestClass()
{ //cpp에서 구현한 생성자는 무시된다.
    TestClass::x = 19;
    std::cout << TestClass::x;
}



/** main.cpp **/
#include "testClass.h"
using namespace std;
int main()
{
    TestClass *t = new TestClass();
}

 

결과:

x = 10

 

 

2. g++ 컴파일 옵션 변경

 

g++로 컴파일할때 직접 링크해줘도 된다. <g++ 메인.cpp 클래스.cpp> 이렇게

 

/** testClass.h **/
#include <iostream>
class TestClass
{
    public:
        int x = 10;
        TestClass();	//헤더에서도 구현하면 오류난다
};


/** testClass.cpp**/
#include "testClass.h"
TestClass::TestClass()
{
    TestClass::x = 19;
    std::cout << TestClass::x;
}

 

결과:

x = 19