CMake variable contents dependent on build/install

997 views Asked by At

Using the $<INSTALL_INTERFACE:...> and $<BUILD_INTERFACE:...> generator expressions I can set target properties to different values depending on whether the target is exported in the current build directory or installed globally. I am writing a custom macro to accompany my CMake package and targets and would like to make the macro behave differently depending on where it is exported (in the build directory) or installed. The macro is contained in a <package>-macros.cmake.in which is included from my <package>-config.cmake file and is configured into the build directory using configure_file and later installed. I tried using the generator expressions in variables set using the configure_file command, but obviously they are not intended to work that way. I assume my requirement is not that uncommon, how is it usually done using CMake?

1

There are 1 answers

2
Tsyvarev On BEST ANSWER

Just create different <package>-config.cmake files for export() and for install(EXPORT). In that files you may have a variable which differentiate them.

You may even create both files from the same pattern using configure_file command with different CMake environment(variables):

<package>-config.cmake.in:

set(IS_BUILD_INTERFACE @IS_BUILD_INTERFACE@)
# other commands, inclusion of other files, etc.

<package>-macros.cmake:

if(IS_BUILD_INTERFACE)
    # Part of build interface
else()
    # Part of install interface
endif()

CMakeLists.txt:

# Prepare the file for build interface exporting
set(IS_BUILD_INTERFACE ON)
configure_file(<package>-config.cmake.in <package>-config.cmake @ONLY)
export(PACKAGE <package>)

# Prepare the file for install interface exporting
set(IS_BUILD_INTERFACE OFF)
configure_file(<package>-config.cmake.in <package>-config.cmake.install @ONLY)
install(FILES <package>-config.cmake.install DESTINATION cmake)