How to set target's compiler preprocessor flags?

I want to compile ‘C’ source file, defining HAVE_CONFIG_H to the C preprocessor. E.g. if gcc is the compiler, I want to pass -DHAVE_CONFIG_H to the compiler. What is the correct portable way to do this, using target_compile_options? In my CMakeLists.txt I am building a library:

    # Static library
    add_library(gsf
                STATIC
                dump_gsf.c  gsf_compress.c  gsf_enc.c  gsf_indx.c
                gsf.c       gsf_dec.c       gsf_geo.c  gsf_info.c)

    # Want to define HAVE_CONFIG_H to the preprocessor
    target_compile_options(gsf option-stuff-goes-here)

    target_include_directories(gsf
                               PUBLIC
                               .
                               ${GMT_INCLUDE_DIR}
                               ${CMAKE_SOURCE_DIR}/src/mbio)

Thanks!

target_compile_definitions

https://cmake.org/cmake/help/latest/command/target_compile_definitions.html

1 Like

This should work for your case

target_compile_definitions(gsf PRIVATE 
         $<$<COMPILE_LANG_AND_ID:C,GNU>:HAVE_CONFIG_H>)

See example from docs

HTH

1 Like

Great - thanks!