1

First of all, I have read this post Why do you need an explicit `-lm` compiler option & this gcc: why is the -lm flag needed to link the math library?. I wanna know why It doesn't happen in case of constants (when I say constants, I mean random floats/doubles)? If you're confused, call it floating-point literals.

Why do we have to use -lm to tell the linker to use math.h functions only when using variables as parameters but not constants? If I use sqrt(N)(N is some number), it compiles fine without any errors but when I pass some variable, let's say sqrt(var), it doesn't. It says:

/usr/bin/ld: /tmp/cc5P9o72.o: in function `main':
sq.c:(.text+0x1b): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status

It should behave the same all the time (I think so, but I am wrong, of-course) as I am using the same function from the same library. Either its variable or constant. I first thought its some kind of compiler optimization (if it's the same value every time, why not calculate it while compiling by some other way, i.e not using the library, as it's not working) but it's doesn't work even if I pass some variable that has a fixed value from beginning to the end. So, I was wrong there. What is actually happening here?

Following is the snippet I tried:

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

int main () {
    float a=9;
    printf("%f",sqrt(a));
    return 0;
}

1 Answers1

3

It is very simple. When you pass the constants many compilers will evaluate it (in such a trivial example when the result is not float inaccuracies and implementation differences prone) compile time without calling the math.h functions.

Even if you do not pass the constants values and compile it with no math error checks and fast math, the compiler will generate the direct float machine code instructions without calling the library ones

Before asking check the generated code for example using the godbolt.org, and usually it will answer all of your questions

0___________
  • 60,014
  • 4
  • 34
  • 74