Search code examples
c++ccmakecmakelists-options

How to make CMakelists.txt to include some *.c and *.h files only for one OS?


I want to include some *.c and *.h files only for Windows OS. But I can't find the way how to do it without creating another target, what entails a mistake

I want to do something like this:

add_executable(${TARGET}
     main.cpp
     mainwindow.cpp
     mainwindow.h
     mainwindow.ui
if (WIN32)
     test.c
     test.h
endif()
)

Is there some way to do this?


Solution

  • The modern CMake solution is to use target_sources.

    # common sources
    add_executable(${TARGET}
         main.cpp
         mainwindow.cpp
         mainwindow.h
         mainwindow.ui
    )
    
    # Stuff only for WIN32
    if (WIN32)
        target_sources(${TARGET}
            PRIVATE test.c
            PUBLIC test.h
        )
    endif()
    

    This should make your CMakeLists.txt files easier to maintain than wrangling variables.