5

I have a project where the CMakeLists.txt attempts to read a file which may or may not be present. It is not a problem for the file to be missing and the script handles either case. This is used to tweak the compilation environment slightly if we can detect a known Linux distribution:

file (READ /etc/redhat-release RHREL)
if (RHREL MATCHES "Red Hat Enterprise Linux Server release 6*")
   # tweak for RHEL6
elseif (RHREL MATCHES "Red Hat Enterprise Linux Server release 7*")
   # tweak for RHEL7
else()
   # either read failed, or we didn't match a known RHEL release
   # fallback to reasonable defaults
endif()

The problem is that when file(READ...) fails it seems to be outputting a message using the SEND_ERROR parameter. This means that my configuration continues into the catch-all else() as I expect, but at the end of configuration CMake refuses to generate a Makefile.

How can I run file(READ) in such a way that I can cope with errors locally and prevent them from failing the entire configuration?

marack
  • 2,024
  • 22
  • 31
  • 1
    You could also check [`CMAKE_HOST_SYSTEM`](https://cmake.org/cmake/help/latest/variable/CMAKE_HOST_SYSTEM.html) global variable. I don't think you actually need to read the `redhat-release` file. – Florian May 02 '16 at 08:03
  • Great idea. I'll change to doing that - but I'd still love to know how to explicitly ignore an error on a command (not just `file(...)`) – marack May 02 '16 at 22:02

2 Answers2

3

You can check if the file exists first (n.b. if it exists but isn't readable you will still have a problem):

if (EXISTS /etc/redhat-release)
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
1

Turning my comment into an answer

In this special case, you could also check CMAKE_HOST_SYSTEM.

The more general answer is you have to move your code into an external CMake script and call it with the all mighty execute_process() command:

FileDumpRedHatRelease.cmake

file(READ /etc/redhat-release RHREL)
execute_process(COMMAND ${CMAKE_COMMAND} -E echo "${RHREL}")

# or if you don't mind the '-- ' leading dashes with STATUS messages
# (because normal CMake messages go to stderr)
#message(STATUS "${RHREL}")

CMakeLists.txt

execute_process( 
    COMMAND ${CMAKE_COMMAND} -P "${CMAKE_CURRENT_LIST_DIR}/FileDumpRedHatRelease.cmake"
    OUTPUT_VARIABLE RHREL
    ERROR_QUIET
)

References

Even those references are all discussing an add_custom_command() command that could fail, you can see the usage of execute_process() and external CMake scripts in such cases:

Community
  • 1
  • 1
Florian
  • 39,996
  • 9
  • 133
  • 149