링커 오류(Linker Error)는 컴파일 후 링크 단계에서 발생하는 오류이다.

C++ 프로그램을 빌드할 때는 컴파일 단계링크 단계가 있다.

링크 오류의 원인

(1) 정의되지 않은 함수/변수 참조 (undefined reference)

// header.h
class Test {
public:
    void show();  // 선언만 있고 정의 없음
};

// main.cpp
#include <iostream>
#include "header.h"

int main() {
    Test t;
    t.show();  // show() 정의가 없으므로 링크 오류 발생
    return 0;
}

(2) 다중 정의 (multiple definition)

// file1.cpp
int globalVar = 10; // 전역 변수 정의

// file2.cpp
int globalVar = 20; // 중복 정의 (링크 오류 발생)

(3) 라이브러리 누락 (undefined reference to function)

#include <math.h>

int main() {
    double result = sqrt(16);  // `-lm` 옵션 없이 빌드하면 링크 오류 발생
    return 0;
}

g++ main.cpp -o main -lm

결과

/usr/bin/ld: /tmp/ccXXXX.o: in function `main':
main.cpp:(.text+0x15): undefined reference to `Test::show()'
collect2: error: ld returned 1 exit status