Yuchen Li
Yuchen Li

Reputation: 21

C program compilation error: undefined reference

I am unable to compile the following simple C code and I don't know why.

#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <math.h>
int main(){
     double result;
     result = cos(0.5);
     printf("asin(0.5) is %f\n", result);
     return 0;
}

The error message I receive after I try to compile is -

In function 

'main':
test.c:(.text+0xlc): undefined reference to 'cos'
collect2: ld

 returned 1 exit status

Upvotes: 2

Views: 3026

Answers (2)

peeyush
peeyush

Reputation: 2931

In general whenever you get undefined reference error it's due to the compiler is not able to find your function definition. So it may be your function ( and you have not typed the spelling of function correctly so you will get this error ) or may be built-in function like you have encountered in this case.
to explore there are various library and their linking are necessary at the time of compilation

whenever you use math function use -lm ( l stands for link and m is for math )
in pthread built-in functions use -lpthread
and so on ... In this case indeed use -lm

gcc -lm test.c

will be able to compile your program .

Upvotes: 0

cnicutar
cnicutar

Reputation: 182714

You need to link with the math library (-lm).

gcc -Wall -Wextra -o test test.c -lm

See this C FAQ.

Upvotes: 14

Related Questions