为什么不建议在头文件中定义宏? [英] Why is it not advised to define macros in header files?
问题描述
Google C ++ Style Guide 指南建议不要在a .h
(头)文件。
The Google C++ Style Guide guide advises that macros must not be defined in a .h
(header) file. What are the cons of doing it?
推荐答案
预处理器将所有包含的源文件按顺序连接在一起。
The preprocessor concatenates all included source files together in order. If you don't undefine a macro, it can apply to any source following where it was first defined.
由于标头通常是库的公共API,因此任何巨集
Since headers are often the public API of a library, any macros you define in your headers could end up in someone else's code, doing unexpected things.
由于意外的事情是好的软件的对立面,你应该:
Since unexpected things are the antithesis of good software, you should either:
- 不使用宏(惯用C ++不应该)
- 在私有范围)或
- 在使用后立即对其进行定义(虽然这使得它们对您自己的代码很无用)
最佳解决方案取决于您的用例。包括守卫和其他简单的,安全的定义通常被排除(类似函数的宏更可能导致问题,但你仍然可以做一些事情像定义TRUE FALSE)。
The best solution depends on your use case. Include guards and other simple, safe defines are typically excluded ( function-like macros are more likely to cause problems, but you can still do something dumb like define TRUE FALSE).
您还可以查看有条件地定义宏,以使它们出现在代码中,但不会成为公共API的一部分。在构建过程中检查变量集或将宏保存在单独的标头中允许其他人可选地,明确地并明确地包括它们,如果宏有助于避免大量的样板,这可以很方便。
You may also look into conditionally defining macros so they are present in your code but don't become part of the public API. Checking for a variable set during your build or keeping macros in a separate header allows others to optionally, explicitly, and knowingly include them, which can be convenient if the macros help avoid a lot of boilerplate.
这篇关于为什么不建议在头文件中定义宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!