为什么在此范围中没有声明“宏”。在我的代码中?

发布于 2025-01-19 04:59:36 字数 450 浏览 5 评论 0原文

我用谷歌搜索了无数遍,但没有找到明确的答案。

我使用:

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

樱花落人离去 2025-01-26 04:59:36

当您在代码中使用m_pi时,例如

double x = M_PI;

,编译器不知道要引用宏。它只是试图找到称为m_pi的东西,并且找不到它。当您想在此范围中使用它时,错误抱怨说,它在此范围中没有声明。

它可以在不同的范围中声明,但是您无法访问它:

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

请注意,由于C ++ 20,您可以使用 std :: Numbers :: Pi_v

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.

又怨 2025-01-26 04:59:36

我似乎找到了解决方案。

微软说,&lt; cmath&gt;(c ++)和&lt; math.h&gt;(c)中的数学常数未定义。

为了为它们定义,您必须将以下宏定义在“包含子句:

#define _USE_MATH_DEFINES

解决我遇到的问题”上方!

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文