Conditionally add files to library in C++ project

c++, cmake

Solution

Use the `set` command to create and update CMake variables:

set(my_SOURCES file1.h file1.cc)

if (GPU_ACCELERATED)
    set(my_SOURCES ${my_SOURCES} gpu_file2.h gpu_file2.cc)
endif()

add_library(my_library ${my_SOURCES})

This will define a `my_SOURCES` variable, if `GPU_ACCELERATED` is true it will update it. Then create your library from the content of the variable.

Problem

I have a CMake C++ project that consist of a library and multiple executable applications. The library contains many files and conditionally depending on whether the user wants to have GPU acceleration the list of files in the library should be different e.g. ``` if (GPU_ACCELERATED) add_library(my_library file1.h file1.cc gpu_file2.h gpu_file2.cc ) else() add_library(my_library file1.h file1.cc ) endif() ``` This is one way of doing it but the problem is that I have a massive number of files and not just `file1.h` `file1.cc` therefore I'd very strongly prefer to avoid duplicating the file listing like that. I would rather like something like this to work (but doesn't) e.g. ``` add_library(my_library file1.h file1.cc if (GPU_ACCELERATED) gpu_file2.h gpu_file2.cc endif() ) ```

Original source