【发布时间】:2015-09-17 13:27:12
【问题描述】:
假设我有两个.hpp 文件:
#ifndef _DEF_FILE_1_
#define _DEF_FILE_1_
inline void some_function_1(){
/*do stuff*/
}
#endif
和
#ifndef _DEF_FILE_2_
#define _DEF_FILE_2_
#ifdef _DEF_FILE_1_
inline void some_function_2(){
/*do stuff using some_function_1()*/
}
#else
inline void some_function_2(){
/*do the same stuff without using some_function_1()*/
}
#endif
#endif
当我不知道包含文件的顺序时,我的问题就出现了,例如:
在main.cpp 我可以有类似的东西:
#include "file1.hpp"
#include "file2.hpp"
int main(){
some_function_2();
/*will call the function that uses some_function_1()*/
}
或
#include "file2.hpp"
#include "file1.hpp"
int main(){
some_function_2();
/*will call the function that doesn't use some_function_1()*/
}
有没有办法确保file1.hpp 和file2.hpp
包括在内,那么some_function_2() 将调用some_function_1()?
PS:一种解决方案是将file1.hpp 包含在file2.hpp 中,但我不能这样做
那是因为我开发了一个可能依赖于也可能不依赖于某个库的代码
最终用户可能有也可能没有。
PPS:我能想到的唯一其他解决方案(即使我不知道如何
实现这一点)将是“删除”some_method_2() 的定义时
包含file1.hpp,然后重新包含file2.hpp。
【问题讨论】:
-
AFAIK 您只能指示用户在您的标题之前包含标题,预处理器将按顺序检查文件,您无法对标题后面的内容做任何事情。
-
你为什么不做第三个标题,你
include它们以正确的顺序,并在main.cpp中使用它?不错的用户名,顺便说一句。 -
OT:您的包含守卫是illegal。
-
这似乎是个糟糕的主意。您可以很容易地破坏 ODR,并且您并不能很好地控制将使用哪个函数实现。为什么你认为你需要这样做? 必须有更好的方法...
-
@LightnessRacesinOrbit 添加
static以绕过我认为可能的 ODR 违规行为。还是个坏主意。
标签: c++ conditional-compilation