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 searching on StackOverflow I have found that I need to add #define _USE_MATH_DEFINES to my code (see example code below). This works fine when compiling normally, but I need to be able to compile with the std=c89 flag for the work that I’m doing.
How should I access M_PI from some C89 code?
A conforming standard library file
math.his not only not required to, but actually must not defineM_PIby default. In this context ‘by default’ means thatM_PImust 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_PIfreely, but should you want to be able to compile the code with a non-conforming compiler, you must first check thatM_PIis not already defined). For convention’s sake, do not defineM_PIas anything other than (the approximation of) pi.