Search code examples
c++cmake

CMake file property is not kept when using target_sources


I have a file distribution.cpp I would like to conditionally compile with CUDA if a flag is set. The following works when adding the file in the source list given to add_library:

add_library(foo STATIC bar.cpp distribution.cpp)
if(${CUDA_FOUND})
    set_source_files_properties(distribution.cpp PROPERTIES LANGUAGE CUDA) 
endif() 

My project has grown, and I am creating an top-level library and adding sources from each directory using target_sources. However, the property on the file set to CUDA no longer holds, and the project will try to build it with a C++ compiler:

add_library(foo STATIC bar.cpp)
# ... In a child directory
target_sources(foo PRIVATE distribution.cpp)
if(${CUDA_FOUND})
    set_source_files_properties(distribution.cpp PROPERTIES LANGUAGE CUDA) 
endif() 

How can I get the desired behaviour of adding additional source files using target_sources, while keeping the language set for that file?


Solution

  • From the documentation:

    By default, source file properties are only visible to targets added in the same directory (CMakeLists.txt). Visibility can be set in other directory scopes using one or both of the following options:

    DIRECTORY <dirs>...

    The source file properties will be set in each of the directories' scopes. CMake must already know about each of these source directories, either by having added them through a call to add_subdirectory() or it being the top level source directory. Relative paths are treated as relative to the current source directory.

    TARGET_DIRECTORY <targets>...

    The source file properties will be set in each of the directory scopes where any of the specified were created (the must therefore already exist).

    So in your case, the following should suffice:

    set_source_files_properties(distribution.cpp TARGET_DIRECTORY foo PROPERTIES LANGUAGE CUDA)