M_PI与math.h一起使用,但在Visual Studio中不与cmath一起使用 [英] M_PI works with math.h but not with cmath in Visual Studio
问题描述
我使用Visual Studio 2010。我已经读过,在C + +中,最好使用< cmath>
,而不是< math。 h>
。
但在程序中,如果我写的话,我试图写入(Win32控制台应用程序,空项目):
#define _USE_MATH_DEFINES
#include< math.h>
它编译,而如果我写
#define _USE_MATH_DEFINES
#include< cmath>
失败,
错误C2065:'M_PI':未声明的标识符
是否正常?如果我使用cmath或math.h是否重要?
UPDATE :如果我在GUI中定义_USE_MATH_DEFINES,它可以工作。有趣的是,我在一个应用程序上检查过这个,我得到了同样的错误。 p>
我花了一会儿检查头部,看看是否有任何东西没有定义_USE_MATH_DEFINES,并且没有找到任何东西。
所以我移动了
#define _USE_MATH_DEFINES
#include< cmath>
是我文件中的第一件事(我不使用PCHs,如果你是你必须在#includestdafx.h之后),然后突然编译完成。
尝试将其在页面上移动。完全不确定为什么会导致问题。
编辑:看出来了。 #include发生在cmath的标题保护内。这意味着#include的列表中的更高级别包括没有指定#define的cmath。 math.h是专门设计的,所以你可以包括它的定义现在改变添加M_PI等。这不是cmath的情况。所以你需要确保你#define _USE_MATH_DEFINES之前,你包括任何其他。希望为你清除它:)
如果只是包括math.h你使用非标准的C / C ++已经指出:)
编辑2 :或者作为大卫在评论中指出,只是使自己成为一个常量,定义的值,你有一个更便携的反正:)
I am using Visual Studio 2010. I have read that in C++ it is better to use <cmath>
rather than <math.h>
.
But in the program I am trying to write (Win32 console application, empty project) if I write:
#define _USE_MATH_DEFINES
#include <math.h>
it compiles, while if I write
#define _USE_MATH_DEFINES
#include <cmath>
it fails with
error C2065: 'M_PI' : undeclared identifier
Is it normal? Does it matter if I use cmath or math.h? If yes, how can I make it work with cmath?
UPDATE: if I define _USE_MATH_DEFINES in the GUI, it works. Any clue why this is happening?
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 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 :)
这篇关于M_PI与math.h一起使用,但在Visual Studio中不与cmath一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!