简体   繁体   中英

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

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

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

See this C FAQ .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM