为什么在此范围中没有声明“宏”。在我的代码中?
我用谷歌搜索了无数遍,但没有找到明确的答案。
我使用:
#include <cmath>
在我的头文件中包含 M_PI
宏(用于 pi 的值)。
我在我在各种函数中创建的类中使用 M_PI
,但是在 g++ 上编译时出现以下错误:
error: 'M_PI' was not declared in this scope
为什么会发生这种情况?
鉴于 M_PI
是一个宏,为什么它定义在哪个范围内很重要?预处理器不是简单地将每次出现的 M_PI
替换为 3.1415926535...
吗?
我应该使用 constexpr
来代替吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您在代码中使用
m_pi
时,例如,编译器不知道要引用宏。它只是试图找到称为
m_pi
的东西,并且找不到它。当您想在此范围中使用它时,错误抱怨说,它在此范围中没有声明。它可以在不同的范围中声明,但是您无法访问它:
请注意,由于C ++ 20,您可以使用
std :: Numbers :: Pi_v
。When you are using
M_PI
in your code, egThen 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:
Note that since C++20 you can use
std::numbers::pi_v
.我似乎找到了解决方案。
微软说,
&lt; cmath&gt;
(c ++)和&lt; math.h&gt;
(c)中的数学常数未定义。为了为它们定义,您必须将以下宏定义在“包含子句:
解决我遇到的问题”上方!
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:
This fixed the problem I was having!