Search code examples
gitcmakeprojectclion

How to check whether the file exists before making it executable in CMake


I got a CLion project. Inside it, I have several files (e.g. Task1.cpp, Task2.cpp). I store them in GitHub in one repository but in different branches (Task1 and Task2 respectively). So when I checkout for another branch on my laptop there's only one left locally. I need to modify CMakeLists.txt so I can build my project without editing it every time I switch my branch. I tried to write it like that:

if(EXISTS Task1.cpp)
  add_executable(Task1 Task1.cpp)
endif()

if(EXISTS Task2.cpp)
  add_executable(Task2 Task2.cpp)
endif()

But it seems that CLion doesn't see (or probably doesn't execute) line add_executable(Task1 Task1.cpp) in case of being in branch Task1.


Solution

  • From the CMake documentation, the file EXISTS check is only well-defined for full paths:

    if(EXISTS path-to-file-or-directory)
    

    True if the named file or directory exists. Behavior is well-defined only for full paths. Resolves symbolic links, i.e. if the named file or directory is a symbolic link, returns true if the target of the symbolic link exists.

    Try using the complete path to these files (which is a safer approach, regardless). If these sources are in the same directory as your current CMake file, you can use CMAKE_CURRENT_SOURCE_DIR:

    if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/Task1.cpp)
      add_executable(Task1 ${CMAKE_CURRENT_SOURCE_DIR}/Task1.cpp)
    endif()
    
    if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/Task2.cpp)
      add_executable(Task2 ${CMAKE_CURRENT_SOURCE_DIR}/Task2.cpp)
    endif()