标头应包含一次
在头文件中,我看到了两种定义宏的主要方法,以避免多次包含该文件。
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我更喜欢第一种方法,因为 ifndef 之后发生什么并不重要,因为它将在之后立即定义。
I prefer the first method, because it doesn't matter what happens after the ifndef because it will be defined straight after.
第一个选项通常由编译器优化,使其行为类似于非标准的
#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.我会选择第一个。
原因:如果您想更改防护名称(例如,将
SOME_CLASS
更改为SOMECLASS
),则不必一直向下滚动到文件末尾即可也改变它。I'd go for the first one.
Reason: If you ever want to change the guard name (say,
SOME_CLASS
toSOMECLASS
), you don't have to scroll all the way down to the end of file to change it too.最好的选择是使用
#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.我更喜欢第一个选择。假设您包含更多文件,并且这些文件又包含包含
#ifndef SOME_CLASS
的文件。我认为,如果
#define SOME_CLASS
与#ifndef 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
.