关于条件编译 (ifndef) 的快速问题

发布于 2024-09-01 08:39:39 字数 224 浏览 2 评论 0原文

这很可能是一个非常愚蠢的问题,但我需要确定。我在头文件中得到了一个类声明,例如。

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

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

发布评论

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

评论(1

谈情不如逗狗 2024-09-08 08:39:40

在文件的末尾。

这种形式的#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.

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