[CMake] Reentrant-safe includes

Robert Dailey rcdailey.lists at gmail.com
Fri Jun 9 14:41:31 EDT 2017


So I have a series of common CMake scripts I use:

pre-setup.cmake
post-setup.cmake

I include pre-setup.cmake at the beginning of the root CMakeLists.txt
and post-setup.cmake is included at the bottom. add_subdirectory() and
other target stuff is done inbetween.

One issue I run into is that these files are sometimes re-entered. For
example, sometimes I have a git submodule with a CMakeLists.txt that
is the root when CMake is run on the submodule by itself, and in
others the submodule's root CMakeLists.txt is just a normal script
included by the parent repository's scripts.

At the moment I'm doing some counting logic to make sure that
pre-setup.cmake and post-setup.cmake are not included multiple times,
if they are not at the root CMakeLists.txt.

Example:

At the top of pre-setup.cmake:

if( NOT DEFINED PRE_SETUP_DEPTH_COUNT )
    set( PRE_SETUP_DEPTH_COUNT 0 )
endif()

math( EXPR PRE_SETUP_DEPTH_COUNT "${PRE_SETUP_DEPTH_COUNT}+1" )

if( PRE_SETUP_DEPTH_COUNT GREATER 1 )
    return()
endif()

And at the top of post-setup.cmake:

math( EXPR PRE_SETUP_DEPTH_COUNT "${PRE_SETUP_DEPTH_COUNT}-1" )
if( PRE_SETUP_DEPTH_COUNT )
    return()
endif()

This seems to work, but is there a simpler/better solution?


More information about the CMake mailing list