Search code examples
gccmath.hc89

Linking Math library to a C90 code using GCC


I would like to compile a simple C90 code utilizing math library:

main.c:

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

int main()
{
  printf("M_PI: %f\n", M_PI);
}

I use GCC compiler and use option -ansi -pedantic to enforce C90 standard.

gcc -ansi -pedantic -lm main.c

But it doesn't compile. The following is the error message:

main.c: In function ‘main’:
main.c:7:25: error: ‘M_PI’ undeclared (first use in this function)
main.c:7:25: note: each undeclared identifier is reported only once for each function it appears in

My question is, why? Does C90 standard prohibits the use of math library?


Solution

  • M_PI isn't defined when strict iso standard is required. Look on this page under trigonometric functions. It is suggested that when using -ansi, just define it yourself:

    #define M_PI 3.14159265358979323846264338327