Exit with custom status code

Hello,

I would like to know if there’s a way to exit at will from a cmake CMakeLists.txt with a status code of my choice.

If the current cmake list corresponds to one of a subdirectory suggesting a nested execution, it’s fine that execution resumes in the parent context with the process status that I supplied to the exit feature and the expected effect on that context level.

Rationale: I’m in a situation where I’m executing a command from a macro and if the result pleases me, I might be inclined to short cut and exit immediately. But, as I suggest, that might not be a fatal condition, it might be an easy win in success instead (zero return status).

To generate a fatal condition is easy with message(FATAL_ERROR …), but I would need something more like a message(SUCCESS_EXIT …) that would return with zero status.

In particular, I must insist that, in my case, I need that behavior to be encapsulatable in a macro for cleanliness of the CMakeLists.txt code at the top level. I could of course do an if that would encompass the rest of the script entirely and only enter the then-clause if my macro didn’t want to exit in shortcut, but wouldn’t be satisfactory obviously.

E.g.:

macro print_help_and_exit_if_asked(opt_help)
    if(NOT "${opt_help}" STREQUAL "")
        print_help()
        exit(0)
    endif()
endmacro()

So, is there any exit() function available or cmake_exit() as another person suggested?

I must insist here that I’m only requesting something very common that is: when entering some conditional part of the code where executing the rest of the script is not expected anymore like printing some help notice or things like that, I would like it to be easy to cut things short. Of course, a giant if can achieve that, but is it necessarily cleaner?

Also the help printing above is just an example, that’s not my true need.

Thanks in advance.

Question: might return() be the answer to my question?

Hello, I implemented cmake_language(EXIT <exitCode>) some times ago (it available since CMake 3.29), check out it here please: https://cmake.org/cmake/help/git-master/command/cmake_language.html#terminating-scripts

In general, no, it just returns you to the outer scope of your directories, and it couldn’t set custom error code if used in top-level CMakeLists.txt scope