[CMake] Adding an individual define to each source file of a library

George PF george.p.f at mail.com
Fri Aug 24 08:40:11 EDT 2018


>>     foreach(x IN LISTS mysrcs)
>>         message("at ${x}")
>>         set_property(SOURCE x APPEND PROPERTY COMPILE_DEFINITIONS "TEST1;TEST2;")
>
> almost there but you forgot to take value of 'x'
>
> set_property(SOURCE ${x} APPEND PROPERTY COMPILE_DEFINITIONS "TEST1;TEST2;")
>
> works for me.

Thank you very much, now it indeed works.


FTR, extracted into a separate 'add_library_with_defs' function in the toplevel CMakeLists.txt


    function(add_library_with_defs libname libtype)
        math(EXPR endindex "${ARGC}-1")
        set(files)
        foreach(index RANGE 2 ${endindex})
            list(GET ARGV ${index} arg)
            list(APPEND files ${arg})
        endforeach()
    
        add_library("${libname}" "${libtype}" "${files}")
    
        get_property(mysrcs TARGET "${libname}" PROPERTY SOURCES)
        foreach(x IN LISTS mysrcs)
            # message("${libname}: at ${x}")
            set_property(SOURCE ${x} APPEND PROPERTY COMPILE_DEFINITIONS TEST1 TEST2)
        endforeach()
    endfunction()


so now it is simplified to: add_library_with_defs(mylib SHARED file1.c file2.c)


More information about the CMake mailing list