Search code examples
cmacrosheaderautotoolsbuild-system

Macro definitions for headers, where to put them?


When defining macros that headers rely on, such as _FILE_OFFSET_BITS, FUSE_USE_VERSION, _GNU_SOURCE among others, where is the best place to put them?

Some possibilities I've considered include

  1. At the top of the any source files that rely on definitions exposed by headers included in that file
  2. Immediately before the include for the relevant header(s)
  3. Define at the CPPFLAGS level via the compiler? (such as -D_FILE_OFFSET_BITS=64) for the:
    1. Entire source repo
    2. The whole project
    3. Just the sources that require it
  4. In project headers, which should also include those relevant headers to which the macros apply
  5. Some other place I haven't thought of, but is infinitely superior

A note: Justification by applicability to make, autotools, and other build systems is a factor in my decision.


Solution

  • If the macros affect system headers, they probably ought to go somewhere where they affect every source file that includes those system headers (which includes those that include them indirectly). The most logical place would therefore be on the command line, assuming your build system allows you to set e.g. CPPFLAGS to affect the compilation of every file.

    If you use precompiled headers, and have a precompiled header that must therefore be included first in every source file (e.g. stdafx.h for MSVC projects) then you could put them in there too.

    For macros that affect self-contained libraries (whether third-party or written by you), I would create a wrapper header that defines the macros and then includes the library header. All uses of the library from your project should then include your wrapper header rather than including the library header directly. This avoids defining macros unnecessarily, and makes it clear that they relate to that library. If there are dependencies between libraries then you might want to make the macros global (in the build system or precompiled header) just to be on the safe side.