1

Why does the following program compile with gcc, ...

#include<stdio.h>
#include<math.h>

void foo(double x) {
   printf("%f", sin(2));
}

int main() {
   foo(1);
}

... while this other program doesn't?

#include<stdio.h>
#include<math.h>

void foo(double x) {
   printf("%f", sin(x));
}

int main() {
   foo(1);
}

It gives the following error message:

/tmp/ccVT7jlb.o: nella funzione "foo":
fun.c:(.text+0x1b): riferimento non definito a "sin"
collect2: error: ld returned 1 exit status*
3
  • Are you using the -lm option when compiling both executables? Commented Feb 19, 2015 at 22:58
  • @wolfPack88 No, I wasn't. I thought standard libraries were automatically linked. Now it works, thanks! Commented Feb 19, 2015 at 23:01
  • 4
    The first one doesn't actually have to link in the math library, because it can optimize sin(2) into a constant. The second one needs to load the sin() function, so you have to tell it to link to libm (or whatever your platform's equivalent is). Commented Feb 19, 2015 at 23:08

1 Answer 1

2

You need to link to libm.so like this

gcc -Wall -Wextra -Werror source.c -o executable -lm

see the -lm

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

1 Comment

Also make sure it's the last option.

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.