Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 524
ravi tandon Avatar asked Jun 09 '15 20:06

ravi tandon


People also ask

Can we define macros in a header file?

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.

Where should macros be defined?

A macro is a fragment of code that is given a name. You can define a macro in C using the #define preprocessor directive.

Why are macros not used in C++?

"Macros are unsafe, have no type checking and should be avoided whenever possible. An alternative to macro is inline function for some use cases."

Should header files have definitions?

Header files should never contain object definitions, only type definitions and object declarations.


1 Answers

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.

like image 134
ssube Avatar answered Oct 11 '22 19:10

ssube