如何识别 C 中重新定义的宏?
我有两个大型框架库,它们的头文件包含在我的项目中。任何一个都可以完美地工作,但同时包含这两个会导致不稳定的行为(但没有与宏相关的错误消息)。
我假设它们都 #define 一个同名的宏。识别有问题的宏的最有效方法是什么?
I have two large framework libraries, whose header files are included in my project. Either one works flawlessly, but including both causes erratic behaviour (but no error message related to the macro).
I assume that they both #define a macro of the same name. What is the most efficient way to identify the problematic macro?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这应该至少会由编译器生成一个警告(如果它们位于同一翻译单元中)。
据我所知,没有直接的方法。
您能给我们一些有关不稳定行为的详细信息吗?到底发生了什么?是什么让您认为这是宏定义?
That should generate at least a warning by the compiler (if they are in the same translation unit).
As far as I know there is no straight-forward way.
Can you please give us some details on the eratic behaviour? What actually happens? What makes you think it's the macro definitions?
如果头文件写得不好并且
#undef SYMBOL ... #define SYMBOL Something-else
那么你就无法跟踪它。简单地 #defining 宏两次至少应该发出警告。您必须更仔细地观察“不稳定的行为”。If the header files are badly written and
#undef SYMBOL ... #define SYMBOL something-else
then you can't trace this. Simply #defining a macro twice should at least issue a warning. You'd have to look more closely at the 'erratic behavior'.尝试查看预处理的输出,以确定在
#include
头文件和不包含头文件时有何不同。使用 gcc 和 MSVC,您可以使用-E
进行编译,以将预处理器输出打印到 stdout。 (它可能有数千行,因此您需要将其通过管道传输到文件中。)Try looking at the preprocessed output to determine what's different about it when you
#include
the header files and when you don't. With gcc and with MSVC, you'd compile with-E
to print the preprocessor output to stdout. (It likely will be many thousands of lines, so you'll want to pipe it to a file.)您应该能够在源代码上运行
ctags
。ctags
可以生成一个标签文件,其中包含 C 文件中宏的名称和位置。您可以通过使用
--c-kinds
选项来控制 ctags 将存储在标签文件中的符号类型。例如。
<代码>
ctags --c-kinds=+d -f 标签 --recurse ./your_source_directory/
然后,您可以在生成的标签文件中搜索重复项。
You should be able to run
ctags
over your source.ctags
can generate a tags file that, amongst other things, contains the names and locations of the macros in your C files.You can control the types of symbols that ctags will store in your tags file through the use of the
--c-kinds
option.eg.
ctags --c-kinds=+d -f tags --recurse ./your_source_directory/
You can then search for duplicates in the resultant tags file.
grep #define ?
你确定问题不是宏以外的东西吗(例如结构打包的编译指示、全局内存分配器、类名的全局命名空间、混乱的语言环境......)
grep for #define ?
are you sure the problem isn't something else than a macro (for example pragmas for structur packing, global memory allocators, global namespace for class names, messing with locale ...)
基本上解决方案(2)将在库之间进行分离。此类冲突的一个示例是 ACE 与 wxWidgets(2.8版本)当强制使用使用不同选项编译的预编译库时(一个库是Unicode,另一个是ASCII)。
Basically solution (2) would make a separation between libraries. An example of such conflict is ACE with wxWidgets (2.8 version) when forced using precompiled libraries that are compiled with different options (one library Unicode the other ASCII).