5.7.8.3 D: Define a Macro

The -Dmacro option allows you to define a preprocessor macro and the -Dmacro=text form of this option additionally allows a user-define replacement string to be specified with the macro. A space may be present between the option and macro name.

When no replacement text follows the macro name, the -Dmacro option defines a preprocessor macro called macro and specifies its replacement text as 1. Its use is the equivalent of placing #define macro 1 at the top of each module being compiled.

The -Dmacro=text form of this option defines a preprocessor macro called macro with the replacement text specified. Its use is the equivalent of placing #define macro text at the top of each module being compiled.

Either form of this option creates an identifier (the macro name) whose definition can be checked by #ifdef or #ifndef directives. For example, when using the option, -DMY_MACRO (or -D MY_MACRO) and building the following code:
#ifdef MY_MACRO
int input = MY_MACRO;
#endif
the definition of the int variable input will be compiled, and the variable assigned the value 1.

If the above example code was instead compiled with the option -DMY_MACRO=0x100, then the variable definition that would ultimately be compiled would be: int input = 0x100;

See 22.1.1 Preprocessor Arithmetic for clarification of how the replacement text might be used.

Defining macros as C string literals requires escaping the quote characters (" ") used by the string. If a quote is intended to be included and passed to the compiler, it should be escaped with a backslash character (\). If a string includes a space character, the string should have additional quotes around it.

For example, to pass the C string, "hello world", (including the quote characters and the space in the replacement text), use -DMY_STRING="\"hello world\"". You could also place quotes around the entire option: "-DMY_STRING=\"hello world\"". These formats can be used on any platform. Escaping the space character, as in -DMY_STRING=\"hello\ world\" is only permitted with macOS and Linux systems and will not work under Windows, and hence it is recommended that the entire option be quoted to ensure portability.

All instances of -D on the command line are processed before any -U options.