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

Viewed 653

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?

3 Answers

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.

You can use a variable for your source file list and append to that variable the OS specific files similar to this:

set( MY_SOURCES 
     main.cpp
     mainwindow.cpp
     mainwindow.h
     mainwindow.ui
)

if (WIN32) 
SET( MY_SOURCES ${MY_SOURCES} 
     test.c
     test.h
)
endif()

add_executable(${TARGET} ${MY_SOURCES})

Instead of using an if block, you can also constrain the sources with a generator expression:

add_executable(${TARGET} PUBLIC
   main.cpp
   mainwindow.cpp
   mainwindow.h
   mainwindow.ui
   $<$<PLATFORM_ID:Windows>:
       test.c
       test.h
  >
)

This approach also works with the target_sources command, if you prefer.

Related