Search code examples
cmakebuild

What's the idiomatic way to compile the same file twice, with different compile definitions?


This answer offers to declare different properties on two different targets but I'm building an old library which needs to compile the same file with two different compile definitions. How to can it with CMake?


Solution

  • You have to add object files as "libraries" and then link them with your main target as usual.

    add_library(foo1 OBJECT foo.c)
    add_library(foo2 OBJECT foo.c)
    
    target_compile_definitions(foo1 PRIVATE "FOO1")
    target_compile_definitions(foo2 PRIVATE "FOO2")
    
    add_executable(main main.c)
    target_link_libraries(main PRIVATE foo1 foo2)