强制C++不需要的宏使用错误

Forcing C++ error on unwanted macro use

本文关键字:错误 C++ 不需要 强制      更新时间:2023-10-16

>我有一个到处使用的宏

   #define DBG(s) do_something_with(s)

但是,在其中一个文件中,我想使其无法使用 - 并导致编译错误

#ifdef DBG
#undef DBG
#define DBG(s) #error "do not use DBG in this file"
#endif

显然,我的例子行不通。有什么建议可以完成这样的事情吗?

在 C++11 中,您可以执行以下操作:

#ifdef DBG
# undef DBG
#endif
#define DBG(s) static_assert(false, "you should not use this macro")

带有错误消息,例如:

C:/Code/Test/src/src/main.cpp: In function 'int main(int, char**)':
C:/Code/Test/src/src/main.cpp:38:16: error: static assertion failed: you should not use this macro
 #define DBG(s) static_assert(false, "you should not use this macro")
                ^
C:/Code/Test/src/src/main.cpp:45:5: note: in expansion of macro 'DBG'
     DBG(42);
     ^

在 C/C++03 中,一个简单的#undef将产生如下结果:

C:/Code/Test/src/src/main.cpp:45:11: error: 'DBG' was not declared in this scope

这可能就足够了。

如果您需要避免预处理器使用 DBG,大多数预处理器都支持您可以使用的 #error 指令,

#ifdef DBG
#error "do not use DBG in this file"
#endif

但是,如果要防止宏在代码中展开,则可以依赖未定义类型的sizeof DBG在编译时失败,

#ifdef DBG
#undef DBG
#define DBG sizeof("Don't use the " + DBG +" macro in this file")
#endif

当然,您可以定义它来执行无效的操作。

然后你会得到编译错误,但它们不会很"清晰"。

像这样:

#undef DBG
#define DBG(s) please_dont_use_dbg_in_this_file()

或者正如评论中指出的那样,只需将其保留为未定义,然后您将收到有关未定义引用的错误:

#undef DBG

这也许可以被认为是更清楚的,我不是100%确定。

只需在.cpp文件中执行此操作即可

#ifdef DBG
#undef DBG
#endif

这样,您的编译将在遇到 DBG 时失败