Search code examples
c++cc-preprocessormeson-build

How do I define a C/C++ preprocessor variable in Meson?


I want to conditionally define a variable that I then can use within C/C++ sources to conditionally compile some code, like this:

#ifdef MY_MESON_VARIABLE
    // some code
#endif

How do I go about actually setting MY_MESON_VARIABLE from Meson build system code such that it becomes accessible to the C preprocessor? I already know how do flow control in Meson, so I just need to know how to set a preprocessor variable.


Solution

  • Meson allows you to define preprocessor variables via compilation arguments. To do this, use add_project_arguments or add_global_arguments, add to Meson.build:

    add_project_arguments('-DMY_MESON_VARIABLE', language: 'c')
    

    The -D before the variable name tells the compiler to define the specified variable.

    The add_project_arguments function adds compilation arguments that will be applied to the entire project.

    This will make MY_MESON_VARIABLE available for #ifdef in C/C++ sources.