Why is it not advised to define macros in header files?

12k views Asked by At

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?

2

There are 2 answers

2
ssube On BEST ANSWER

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:

  1. Not use macros (idiomatic C++ really shouldn't)
  2. Define them in a private scope (always prefer private) or
  3. Undefine them immediately after use (although this makes them largely useless for your own code)

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.

0
AltF4 On

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.