Cpp,执行预处理器评估顺序

Cpp, enforcing a preprocessor evaluation order

给定以下代码片段,每个 .h 和 .cpp 文件中都有预处理器欺骗,是否可以按照调用函数的顺序评估关联的预处理器函数?对于必须维护它的程序员来说,我该如何执行它而不会有很多困难?

#include "Foo.h"
#include "Bar.h"
#include "Qux.h"

int main()
{
    Foo foo = Foo();
    Bar bar{};
    foo.doFoo();
    Qux::doQux();
    return 0;
}

编辑: 澄清一下,让我们假设 Foo、Bar、Qux .cpp 和 .h 声明预处理器定义。 我可以强制预处理器在 Qux.h 之前评估 Foo.h、Foo.cpp、Bar.h 和 Bar.cpp 吗?

Can I enforce Foo.h, Foo.cpp, Bar.h and Bar.cpp are evaluated before Qux.h by the preprocessor?

不是通过预处理器,不是。执行这样的解析顺序的通常方法是通过 #include 指令——例如,如果你想保证 Foo.hBar.h 总是在 Qux.h 之前被解析,然后在 Qux.h 的顶部添加 #include 行以保证它:

// Qux.h
#ifndef QUX_H
#define QUX_H

#include "Foo.h"
#include "Bar.h"

[...]

#endif

Can I enforce Foo.h, Foo.cpp, Bar.h and Bar.cpp are evaluated before Qux.h

您可以在 Qux.h 之前强制包含 Foo.hBar.h,一种方法是:

1) 放在开头(甚至结尾)Foo.h:

#ifndef FOO_H_INCLUDED
#define FOO_H_INCLUDED
#endif

2) 放在开头(或结尾)Bar.h:

#ifndef BAR_H_INCLUDED
#define BAR_H_INCLUDED
#endif

(以上其实也可以当inclusion guard,如果你想拥有的话)

3) 签入 Qux.h:

#ifndef FOO_H_INCLUDED
#error Please include Foo.h before Qux.h!
#endif

#ifndef BAR_H_INCLUDED
#error Please include Bar.h before Qux.h!
#endif

另一种方式 - 只需添加到 Qux.h:

的开头
#include "Foo.h"
#include "Bar.h"

强制执行 Foo.hBar.h 总是在 Qux.h 的其余部分之前处理(无需检查包含 defs)。

Foo.cppBar.cpp 与此无关,它们是在单独的编译器(和预处理器)中构建的单独翻译单元 运行.