Build flags

Build flags

Sergey Abbakumov

Conditional compilation is used in many C/C++ projects. I'm gonna tell you how it is implemented in Chromium.

Conditional compilation in general in C/C++ is the result of the preprocessor work, which, depending on certain macros, turns a section of text on or off.

Usually it looks like this:

#ifndef NDEBUG  // Debug mode is on.
#endif  // NDEBUG

#ifdef NDEBUG  // Debug mode is off.
#endif  // NDEBUG


There is another option:

#if defined (NDEBUG)  // Debug mode is on.
#endif  // defined (NDEBUG)



If you made a mistake in writing the macro name, in the worst case you will not know it: there will be no compilation error, only the program will behave strangely.


In Chromium they came up with an interesting preprocessor trick: https://cs.chromium.org/chromium/src/build/buildflag.h?q=buildfla&sq=package:chromium&l=45. Then if you make a mistake, the preprocessor will throw an error.


// Implementation:
#define BUILDFLAG_CAT_INDIRECT(a, b) a ## b
#define BUILDFLAG_CAT(a, b) \
    BUILDFLAG_CAT_INDIRECT (a, b)
#define BUILDFLAG(flag) \
    (BUILDFLAG_CAT(BUILDFLAG_INTERNAL_, flag) ())

// Usage:
#if BUILDFLAG(SOME_FEATURE)  // OK.
#endif // BUILDFLAG(SOME_FEATURE)

#if BUILDFLAG(UNDEFINED)  // Compilation error.
#endif  // BUILDFLAG(UNDEFINED)



In general, the full name of the macro is defined in the special section in BUILD.gn file.

But you can use this idea separately:

https://github.com/sabbakumov/rst/tree/master/rst/BuildFlag.


Telegram channel: https://t.me/sea_plus_plus

Report Page