I\'m using C and trying to get access to the constant M_PI (3.14159...). I have imported the math.h header file, but the M_PI constant was still undefined. Through some sear
I fail to see what the problem is here; there is no incompatability between -std=c89 and _USE_MATH_DEFINES, one defines what language the compiler will compile, the other defines what parts of math.h get enabled.
Those parts that are enabled are not defined as part of the ISO C standard library, but that is not the same thing as not being standard C language, language and library are separate entities in C. It is no less C89 compliant than it would be if you had defined your own macros in your own header.
I would however suggest that you define the macro on the command-line rather than in the code:
-std=c89 -D_USE_MATH_DEFINES
If you ever encounter a math.h implementation that does not define M_PI, then that is easily fixed without code modification by similarly using command line defined macros:
-std=c89 -DM_PI=3.14159265358979323846
I would go for
#ifndef M_PI
# define M_PI 3.14159265358979323846
#endif
M_PI
is not required by the C standard, it's just a common extension, so if you want to be standard you shouldn't rely on it. However, you can easily define your own #define
for it, last time I checked it was a universal constant so there's not much space for confusion. :)
A conforming standard library file math.h
is not only not required to, but actually must not define M_PI
by default. In this context 'by default' means that M_PI
must only get defined through compiler-specific tricks, most often undefined behavior through the use of reserved identifiers.
Just define the constant yourself (you can use the name M_PI
freely, but should you want to be able to compile the code with a non-conforming compiler, you must first check that M_PI
is not already defined). For convention's sake, do not define M_PI
as anything other than (the approximation of) pi.