2

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
2
  • 4
    Btw, I hope you noticed that you're calculating a cosine, and saying the result is the arc-sine, which are not the same thing. Commented Jul 17, 2011 at 19:24
  • This is actually a linker error rather than a compiler error. That is made clear because the error is coming from ld, the linker. Invariably the reason is a missing import library. Commented Jul 17, 2011 at 19:26

2 Answers 2

14

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

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

See this C FAQ.

Sign up to request clarification or add additional context in comments.

Comments

0

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 .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.