强制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
但是,如果要防止宏在代码中展开,则可以依赖未定义类型的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 时失败
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 错误:未在此范围内声明'reverse'