关于条件编译 (ifndef) 的快速问题
这很可能是一个非常愚蠢的问题,但我需要确定。我在头文件中得到了一个类声明,例如。
#ifndef file_H
#define file_H
class ex{
private:
public:
};
#endif
我被要求在同一个文件中编写方法定义,我已经这样做了,我的问题是“#endif”是否保留在类声明之后的位置,或者在之后放在我的文件末尾类方法定义?
This is quite probably a very silly question but I need to be sure. I've been given a class declaration in a header file eg.
#ifndef file_H
#define file_H
class ex{
private:
public:
};
#endif
and I've been required to write the method definitions in the same file, which I have done, my question is does the "#endif" stay where it is just after the class declaration or does it go at the end of my file after the class method definitions?.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在文件的末尾。
这种形式的#ifndef 模式的目标是防止相同的声明或定义在编译单元中出现两次的情况。
这样做是因为一个 C 文件可能包含多个 H 文件,而链上的某个位置又可能包含相同的文件。如果您只是在没有这些的情况下运行预处理器,您将拥有 H 文件的多个副本。这样,您就有多个副本,但预处理器会忽略第一次遇到后的所有内容。
由于您不应该多次定义任何内容,因此如果您必须将方法定义放在头文件中,请将它们放在
#endif
中。At the end of the file.
The goal of this form of this
#ifndef
pattern is to prevent a situation where the same declaration or definition appears twice in a compilation unit.This is done because a C file may include several H files, which somewhere up the chain may in turn include the same file. IF you simply ran the preprocessor without these, you would have multiple copies of the H file. This way, you have multiple copies, but the preprocessor ignores everything after the first encounter.
Since you're not supposed to be defining anything more than once, if you have to place method definitions in the header file, put them within the
#endif
.