检查何时同时包含两个标头
我需要根据在不同头文件中声明的两个相关的宏预处理器 #define 进行断言...代码库很大,如果我能找到一个放置断言的地方,那就太好了其中已经包含两个标头,以避免不必要的污染命名空间。
仅检查文件是否显式包含两者可能还不够,因为其中一个(或两者)可能包含在嵌套包含层次结构的上一层中。
我知道编写一个脚本来检查这一点并不太难,但如果已经有一个工具可以完成这项工作,那就更好了。
示例:
文件 foo.h
#define FOO 0xf
文件 bar.h
#define BAR 0x1e
我需要将某个地方(在哪里并不重要)放置如下内容:
#if (2*FOO) != BAR
#error "foo is not twice bar"
#endif
是的,我知道这个例子很愚蠢,因为它们可以被替换,因此一个是从另一个派生的,但是假设包含可以从不受我控制的不同位置生成,我只需要检查它们在编译时是否匹配...而且我不想只添加一个包含另一个,因为它可能与我之前未编写的代码冲突,所以这就是为什么我想找到一个两者都已存在的文件。
简而言之:如何找到包含(直接或间接)其他两个文件的文件?
I need to do an assertion based on two related macro preprocessor #define
's declared in different header files... The codebase is huge and it would be nice if I could find a place to put the assertion where the two headers are already included, to avoid polluting namespaces unnecessarily.
Checking just that a file includes both explicitly might not suffice, as one (or both) of them might be included in an upper level of a nesting include's hierarchy.
I know it wouldn't be too hard to write an script to check that, but if there's already a tool that does the job, the better.
Example:
file foo.h
#define FOO 0xf
file bar.h
#define BAR 0x1e
I need to put somewhere (it doesn't matter a lot where) something like this:
#if (2*FOO) != BAR
#error "foo is not twice bar"
#endif
Yes, I know the example is silly, as they could be replaced so one is derived from the other, but let's say that the includes can be generated from different places not under my control and I just need to check that they match at compile time... And I don't want to just add one include after the other, as it might conflict with previous code that I haven't written, so that's why I would like to find a file where both are already present.
In brief: how can I find a file that includes (direct or indirectly) two other files?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于您的两个包含文件可能都受到 #define 保护的保护,因此您可以检查这两个头文件中的每一个(如果基于
#ifdef THE_OTHER_GUARD_NAME
包含另一个头文件),并发出警告(或错误,无论您喜欢哪个)如果您检测到它已包含在内。As you have both of your includes probably protected by #define guards, you might check in each of those two header files if the other one is included based on
#ifdef THE_OTHER_GUARD_NAME
, and issue warning (or error, whichever you prefer) if you detected it is included.如果您使用的是 Unix 或类 Unix 系统,则可以使用一个名为
makedepend
的实用程序。http://en.wikipedia.org/wiki/Makedepend
如果您使用的是 Windows,则有一个名为 makedep 的 Sourceforge 项目可能会起作用。
If you are on a Unix or Unix-alike system, there is a utility called
makedepend
you can use.http://en.wikipedia.org/wiki/Makedepend
If you are on Windows, there's a Sourceforge project called makedep that might work.
#pragma Once 运算符怎么样?之后您可能会忘记担心多个头文件定义......
What about #pragma once operator? After that you may forget to worry about multiply header file definitions...