[C] <math.h> ERROR: Undefined reference to '{Function}' 오류 해결

발견된 문제

ERROR: Undefined Reference to 'exp'

ERROR: Undefined Reference to 'log'

ERROR: Undefined Reference to 'sqrt'

ERROR: Undefined Reference to 'pow'

ERROR: Undefined Reference to 'abs'

ERROR: Undefined Reference to 'sin'

ERROR: Undefined Reference to 'cos'

etc.. 링크 오류

해결 방법

gcc example.c -o example -lm

위 예제와 같이 "-lm"을 추가해 링크 옵션을 추가해주자.

Code Runner 의 경우

Visual Studio Code 환경설정에 들어가서 Code Runner의 타입별 작동 명령어를 수정해주자.

"c": "cd $dir && gcc $fileName -lm -o $fileNameWithoutExt && $dir$fileNameWithoutExt"

문제 기술

gcc 컴파일 시 <math.h> 헤더 파일이 링크가 되지 않은 경우이다.

 

수식을 담당하는 libm(math library)는 컴파일시 사용되는 libc에서 별도로 분리되어 <math.h> 헤더가 선언되어도 링크 과정에서 libm 을 불러올 수 없다.

 

따라서 컴파일 명령어 링크 옵션에 -lm 을 추가하여 math library를 링크한다고 알려주면 된다.