CPack: Exclude INSTALL commands from subdirectory (googletest directory)

Updated: As noted in the other answer, it seems that EXCLUDE_FROM_ALL option is the most direct and correct way for disable install in the subproject in the subdirectory:

add_subdirectory(googletest EXCLUDE_FROM_ALL)

Previous solutions

If you don't need tests in your project's release (which you want to deliver with CPack), then include googletest subdirectory conditionally, and set conditional to false when packaging:

...
if(NOT DISABLE_TESTS)
    add_subdirectory(googletest)
endif()

packaging with

cmake -DDISABLE_TESTS=ON <source-dir>
cpack

Alternatively, if you want tests, but don't want to install testing infrastructure, you may disable install command via defining macro or function with same name:

# Replace install() to do-nothing macro.
macro(install)
endmacro()
# Include subproject (or any other CMake code) with "disabled" install().
add_subdirectory(googletest)
# Restore original install() behavior.
macro(install)
    _install(${ARGN})
endmacro()

This approach has also been suggested in CMake mailing.

According to the comments, that way with replacing CMake command is very tricky one and may to not work in some cases: either parameters passed to the modified install are parsed incorrectly or restoring install is not work and even following installs are disabled.


So there is the macro option @Tsyvarev mentioned that was originally suggested here:

# overwrite install() command with a dummy macro that is a nop
macro (install)
endmacro ()

# configure build system for external libraries
add_subdirectory(external)

# replace install macro by one which simply invokes the CMake
install() function with the given arguments
macro (install)
  _install(${ARGV})
endmacro(install)

Note ${ARGV} and ${ARGN} are the same but the docs currently suggest using ${ARGN}. Also the fact that macro-overwriting prepends _ to the original macro name is not documented, but it is still the behaviour. See the code here.

However, I never got the above code to work properly. It does really weird things and often calls install() twice.

An alternative - also undocumented - is to use EXCLUDE_FROM_ALL:

add_subdirectory(external EXCLUDE_FROM_ALL)

According to some comment I found somewhere this disables install() for that subdirectory. I think what it actually does is set EXCLUDE_FROM_ALL by default for all the install() commands which also probably does what you want. I haven't really tested it, worth a shot though.