'M_PI flagged as undeclared identifier

When I compile the code below, I got these error messages:

(Error  1   error C2065: 'M_PI' : undeclared identifier 
2   IntelliSense: identifier "M_PI" is undefined)

What is this?

#include <iostream>
#include <math.h>

using namespace std;

double my_sqrt1( double n );`enter code here`

int main() {
double k[5] = {-100, -10, -1, 10, 100};
int i;

for ( i = 0; i < 5; i++ ) {
    double val = M_PI * pow( 10.0, k[i] );
    cout << "n: "
         << val
         << "\tmysqrt: "
         << my_sqrt1(val)
         << "\tsqrt: "
         << sqrt(val)
         << endl;
}

return 0;
}

double my_sqrt1( double n ) {
int i;
double x = 1;


for ( i = 0; i < 10; i++ ) {
    x = ( x + n / x ) / 2;
}

return x;
}


Solution 1:[1]

It sounds like you're using MS stuff, according to their docs

Math Constants are not defined in Standard C/C++. To use them, you must first define _USE_MATH_DEFINES and then include cmath or math.h.

So you need something like

#define _USE_MATH_DEFINES
#include <cmath>

as a header.

Solution 2:[2]

math.h does not define M_PI by default.

So go with this:

#ifndef M_PI
    #define M_PI 3.14159265358979323846
#endif

This will handle both cases either your header have M_PI defined or not.

Solution 3:[3]

M_PI is supported by GCC too, but you've to do some work to get it

#undef __STRICT_ANSI__
#include <cmath>

or if you don't like to pollute your source file, then do

g++ -U__STRICT_ANSI__ <other options>

Solution 4:[4]

As noted by shep above you need something like

#define _USE_MATH_DEFINES
#include <cmath>

However you also include iostream.

iostream includes a lot of stuff and one of those things eventually includes cmath. This means that by the time you include it in your file all the symbols have already been defined so it is effectively ignored when you include it and the #define _USE_MATH_DEFINES doesn't work

If you include cmath before iostream it should give you the higher precision constants like M_PI

#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>

Solution 5:[5]

Use this include for Windows 10 (and Windows 11):

#include <corecrt_math_defines.h>

Solution 6:[6]

I used C99 in NetBeans with remote linux host with its build tools.
Try adding #define _GNU_SOURCE and add the -lm during linking.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shep
Solution 2 Jabberwocky
Solution 3
Solution 4 Metric Crapton
Solution 5
Solution 6 Eruthon