0

I have a program which will run when compiled (without -lm flag) when the pow() function is out in the main() function, like so:

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

int main(void)
{

    double test = pow(16, 5);
    printf("%f\n", test);

}

It compiles and runs fine:

$ gcc 2-3.c -o 2-3 && ./2-3
1048576.000000

However when pow() is inside a function the program won't compile:

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

double in_function(int val);

int main(void)
{

    double test;

    test = in_function(5);
    printf("%f\n", test);

}


double in_function(int val) {

    double n;

    n = pow(16, val);

    return n;

}

Try to compile:

$ gcc 2-3.c -o 2-3 && ./2-3
/tmp/ccCEDMJ8.o: In function `in_function':
2-3.c:(.text+0x65): undefined reference to `pow'
collect2: error: ld returned 1 exit status

I realize that I need to add the -lm flag to gcc to make it work, but I didn't need to add -lm to the first program at all. Why is that?

hawruh
  • 185
  • 8
  • Compile-time evaluation? In your first example, everything needed to compute the result is known at compile time. – Adrian Mole Jul 03 '21 at 15:10
  • 1
    `pow(16, 5)` is computed by the compiler (at compile time); `pow(16, val)` must be computed by the code in the math library (at run time). – pmg Jul 03 '21 at 15:10
  • 1
    Try `double in_function(void) { return pow(16, 5); }` – pmg Jul 03 '21 at 15:16

0 Answers0