繁体   English   中英

在不必要的宏使用上强制C ++错误

[英]Forcing C++ error on unwanted macro use

我到处都有一个宏

   #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

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

#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时失败

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM