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?