10

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?

0

2 Answers 2

16

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What is a good example of conditionally including the macros in our code such that it does not become a part of the public API ?
You can use something as simple as an ifdef FOO_MACROS guard around the macros in a header, then define that as part of your build. Otherwise, put them in a header that your source files (but not your public headers) include, allowing you access but not distributing them.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.