gimmeamilk
gimmeamilk

Reputation: 2120

cmake: check if file exists at build time rather than during cmake configuration

I have a custom build command that needs to check if a certain file exists. I tried using

IF(EXISTS "/the/file")
...
ELSE()
...
ENDIF()

but that test is only evaluated one; when cmake is first run. I need it to perform the test every time a make is done. What's the method to check at make-time? Thanks.

Upvotes: 9

Views: 14070

Answers (3)

skaravos
skaravos

Reputation: 497

[@Frazers] answer is great if you need to add custom logic inside the if(EXISTS). However, if you just need your build to fail if a single file is missing you can use the cmake -E command line mode to compare the file with itself.

This will make sure the build always stops if the provided file doesn't exist, it's cross-platform safe and works in every version of cmake since 3.0.

set(_fileToCheck "foo.txt")
add_custom_command(TARGET YourTarget
  PRE_BUILD
  COMMAND ${CMAKE_COMMAND} -E compare_files ${_fileToCheck} ${_fileToCheck}
  WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
  COMMENT "Checking if ${_fileToCheck} exists, build will fail if it doesn't"
)

Upvotes: 2

Cameron Lowell Palmer
Cameron Lowell Palmer

Reputation: 22246

A similar idea

You're going to need add_custom_command, but if you're willing to be a little Unix specific you can always use test.

set(FileToCheck "/the/file")
add_custom_command( OUTPUT output.txt
    COMMAND test -e output.txt || echo "Do something meaningful"
    COMMENT "Checking if ${FileToCheck} exists...")

Upvotes: 4

Fraser
Fraser

Reputation: 78488

You can use add_custom_command to invoke CMake itself in script mode by using the -P command line option.

So your command would be something like:

set(FileToCheck "/the/file")
add_custom_command(TARGET MyExe
                   POST_BUILD
                   COMMAND ${CMAKE_COMMAND}
                       -DFileToCheck=${FileToCheck}
                       -P ${CMAKE_CURRENT_SOURCE_DIR}/check.cmake
                   COMMENT "Checking if ${FileToCheck} exists...")

and your script file "check.cmake" would be something like:

if(EXISTS ${FileToCheck})
  message("${FileToCheck} exists.")
else()
  message("${FileToCheck} doesn't exist.")
endif()

Upvotes: 17

Related Questions