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

喜欢而已 提交于 2020-12-05 11:26:46

问题


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.


回答1:


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()



回答2:


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...")


来源:https://stackoverflow.com/questions/18785168/cmake-check-if-file-exists-at-build-time-rather-than-during-cmake-configuration

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!