3

I am trying to use the Constant M_LN2 from the math.h library but always seem to get a compiler error. The code is:

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

int main(){

double x = M_LN2;
printf("%e",x);

return 0;
}

compiling with gcc on ubuntu

gcc -std=c99 lntester.c -o lntester -lm

getting output:

error: 'M_LN2' undeclared 

any help in understanding why this is happening would be greatly appreciated.

As stated below the if def were not getting defined and using gcc and c99 were causing the issue. Below is the compile code that solved the issue and allowed me to use c99.

gcc -std=c99 -D_GNU_SOURCE lntested.c -o lntester -lm
CSnewb
  • 147
  • 4
  • 13

1 Answers1

5

any help in understanding why this is happening would be greatly appreciated.

You can open /usr/include/math.h and try to found definition of M_LN2. For me it is defined and wrapped by condition macros:

#if defined __USE_BSD || defined __USE_XOPEN
...
# define M_LN2          0.69314718055994530942  /* log_e 2 */
...
#endif

When you compile your code with option -std=c99 neither __USE_BSD no __USE_XOPEN defined, so all variables which wrapped by if define not defined too.

You can compile your code without -std=c99 option or with -std=gnu99 option instead.

Gluttton
  • 5,739
  • 3
  • 31
  • 58
  • Okay, so i have posted the solution to the issue in the code. Thanks for helping understand that the if defs were the reason it was happening. – CSnewb Sep 06 '14 at 22:12