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?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Macro expansion in elixir: how to define 2 macros
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
For the same reasons that using statements should not be in header files: namespace pollution. If you want to use macros in a header file, make sure that you undefine them at the end of the header, this way they will not be included erroneously. If you simply want to define them in a header and use them in cpp files make sure that the "macros.h" is never included in any header.
The who point of this is that a end user of what ever public API you are developing may not want or expect, for example, sum(a, b) to expand to (a) + (b). Finding the source of one's own macro error can be a nightmare, finding someone else can be almost impossible.
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.
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:
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).
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.