标头应包含一次

发布于 2024-11-09 11:57:37 字数 246 浏览 5 评论 0原文

在头文件中,我看到了两种定义宏的主要方法,以避免多次包含该文件。

1.

#ifndef SOME_CLASS
#define SOME_CLASS
//code ...
#endif

2.

#ifndef SOME_CLASS
//code...
#define SOME_CLASS
#endif

哪一个更可取,为什么?

In header files I've seen two main ways for defining macro to avoid including the file more than once.

1.

#ifndef SOME_CLASS
#define SOME_CLASS
//code ...
#endif

2.

#ifndef SOME_CLASS
//code...
#define SOME_CLASS
#endif

Which is more preferable and why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(5

云归处 2024-11-16 11:57:37

我更喜欢第一种方法,因为 ifndef 之后发生什么并不重要,因为它将在之后立即定义。

I prefer the first method, because it doesn't matter what happens after the ifndef because it will be defined straight after.

你げ笑在眉眼 2024-11-16 11:57:37

第一个选项通常由编译器优化,使其行为类似于非标准的#pragma Once

在递归包含的情况下也更安全。如果在 //code... 部分中,您包含另一个标头,其中包含 .... 其中包含您当前正在编辑的标头,则第二个版本将不起作用。

The first option is commonly optimized by compilers to behave like the non-standard #pragma once.

It is also safer in case of recursive includes. If, in the //code... part, you include another header which includes .... which includes the header you're currently editing, then the second version won't work.

趴在窗边数星星i 2024-11-16 11:57:37

我会选择第一个。

原因:如果您想更改防护名称(例如,将 SOME_CLASS 更改为 SOMECLASS),则不必一直向下滚动到文件末尾即可也改变它。

I'd go for the first one.

Reason: If you ever want to change the guard name (say, SOME_CLASS to SOMECLASS), you don't have to scroll all the way down to the end of file to change it too.

找回味觉 2024-11-16 11:57:37

最好的选择是使用#pragma Once。使用#define,在使用多个库时必须非常小心,因为防护名称可能不是唯一的。

The best option is to use #pragma once. With #define you must be very careful when using multiple libraries as the guard name may not be unique.

陌路黄昏 2024-11-16 11:57:37

我更喜欢第一个选择。假设您包含更多文件,并且这些文件又包含包含 #ifndef SOME_CLASS 的文件。

我认为,如果 #define SOME_CLASS#ifndef SOME_CLASS 不相邻,那么很容易发现包含错误。

// SomeClass.h
#ifndef SOME_CLASS
#include "OtherFile.h" // will eventually lead to #include "SomeClass.h"
#define SOME_CLASS

... boat load of code here...

#endif // SOME_CLASS

I prefer the first option. Suppose you include more files, and these files in turn include the file containing #ifndef SOME_CLASS.

I think it's fairly easy to spot include errors, if the #define SOME_CLASS isn't adjacent to #ifndef SOME_CLASS.

// SomeClass.h
#ifndef SOME_CLASS
#include "OtherFile.h" // will eventually lead to #include "SomeClass.h"
#define SOME_CLASS

... boat load of code here...

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