Home > Net >  Why is a macro "not declared in this scope" in my code?
Why is a macro "not declared in this scope" in my code?

Time:04-06

I have googled to no end but have not found a definitive answer.

I use:

#include <cmath>

to include the M_PI macro (for the value of pi) in my header file.

I use M_PI in the class I have created in various functions, but when compiling on g I get the following error:

error: 'M_PI' was not declared in this scope

Why is this happening?

Given M_PI is a macro, why would it matter in which scope it is defined in? Doesn't the preprocessor simply replace every occurrence of M_PI with 3.1415926535...?

Should I use a constexpr instead?

CodePudding user response:

When you are using M_PI in your code, eg

double x = M_PI;

Then the compiler does not know that you want to refer to a macro. It merely tries to find something called M_PI and doesn't find it. As you want to use it in this scope, the error complains that it is not declared in this scope.

It could be declared in a different scope, but then you cannot access it:

{
   double M_PI = 3;
}
double x = M_PI;   // M_PI is not declared in this scope

Note that since C 20 you can use std::numbers::pi_v.

CodePudding user response:

I seem to have found a solution.

Microsoft says that math constants in <cmath> (C ) and <math.h> (C) are not defined by default.

For them to be defined, you must define the following macro ABOVE the include clause:

#define _USE_MATH_DEFINES

This fixed the problem I was having!

  • Related