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?
Inclusion of header files. These are files of declarations that can be substituted into your program. Macro expansion. You can define macros, which are abbreviations for arbitrary fragments of C code, and then the C preprocessor will replace the macros with their definitions throughout the program.
A macro is a fragment of code that is given a name. You can define a macro in C using the #define preprocessor directive.
"Macros are unsafe, have no type checking and should be avoided whenever possible. An alternative to macro is inline function for some use cases."
Header files should never contain object definitions, only type definitions and object declarations.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With