0

I found a very strange thing. When I use the log function in the math.h library, I cannot use variables.

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

int main(){
    int b=100;
    double a = log10(100)/log10(10);
    printf("%lf",a);
    return 0;
}

The above code works fine. But the following code reports an error.

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

int main(){
    double b=100;
    double a = log10(b)/log10(10);//Just change 100 to variable b
    printf("%lf",a);
    return 0;
}

The error is

/usr/local/bin/ld: /tmp/cc8j9x4e.o: in function `main':
ctest.c:(.text+0x19): undefined reference to `log10'
collect2: error: ld returned 1 exit status
Gerrie
  • 736
  • 3
  • 18
  • 2
    You sure both are using same compilation statement? `-lm` might be needed, – Sourav Ghosh Nov 11 '20 at 12:26
  • Or maybe you kept `b` as `int` and then decided to compile as C++ – Lundin Nov 11 '20 at 12:28
  • 1
    It seems that gcc will calculate `log10(100)` at compile time even without optimization, but it doesn't calculate `double b =100; log10(b);` https://godbolt.org/z/7W7xdv – mch Nov 11 '20 at 13:25

0 Answers0