Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

file

exists

cmake

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.

like image 741
gimmeamilk Avatar asked Sep 13 '13 11:09

gimmeamilk


People also ask

How to check if a file or directory exists in CMake?

From the CMake documentation, the file EXISTS check is only well-defined for full paths: 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.

What does the if command do in CMake?

Any non-integer version component or non-integer trailing part of a version component effectively truncates the string at that point. The if command was written very early in CMake's history, predating the $ {} variable evaluation syntax, and for convenience evaluates variables named by its arguments as shown in the above signatures.

How do I use relative paths in CMake?

If these sources are in the same directory as your current CMake file, you can use CMAKE_CURRENT_SOURCE_DIR: @МаркТюков Yes, relative paths do work in commands such as add_executable () and add_library ().

What is variable expansion in CMake?

Variable Expansion ¶ The if command was written very early in CMake's history, predating the $ {} variable evaluation syntax, and for convenience evaluates variables named by its arguments as shown in the above signatures. Note that normal variable evaluation with $ {} applies before the if command even receives the arguments.


1 Answers

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()
like image 113
Fraser Avatar answered Oct 01 '22 00:10

Fraser