M_PI works with math.h but not with cmath in Visual Studio
With CMake it would just be
add_compile_definitions(_USE_MATH_DEFINES)
in CMakeLists.txt
.
This works for me:
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
cout << M_PI << endl;
return 0;
}
Compiles and prints pi
like is should: cl /O2 main.cpp /link /out:test.exe
.
There must be a mismatch in the code you have posted and the one you're trying to compile.
Be sure there are no precompiled headers being pulled in before your #define
.
Consider adding the switch /D_USE_MATH_DEFINES to your compilation command line, or to define the macro in the project settings. This will drag the symbol to all reachable dark corners of include and source files leaving your source clean for multiple platforms. If you set it globally for the whole project, you will not forget it later in a new file(s).
Interestingly I checked this on an app of mine and I got the same error.
I spent a while checking through headers to see if there was anything undef'ing the _USE_MATH_DEFINES
and found nothing.
So I moved the
#define _USE_MATH_DEFINES
#include <cmath>
to be the first thing in my file (I don't use PCHs so if you are you will have to have it after the #include "stdafx.h"
) and suddenly it compile perfectly.
Try moving it higher up the page. Totally unsure as to why this would cause issues though.
Edit: Figured it out. The #include <math.h>
occurs within cmath's header guards. This means that something higher up the list of #includes is including cmath
without the #define
specified. math.h
is specifically designed so that you can include it again with that define now changed to add M_PI
etc. This is NOT the case with cmath
. So you need to make sure you #define _USE_MATH_DEFINES
before you include anything else. Hope that clears it up for you :)
Failing that just include math.h
you are using non-standard C/C++ as already pointed out :)
Edit 2: Or as David points out in the comments just make yourself a constant that defines the value and you have something more portable anyway :)