CMAKE: a custom target to install at different location

Viewed 185

I am porting our product from using Makefiles to CMAKE. With Makefile we have 'install' target to move stuff to some location on user's machine and 'deploy' - to some fixed location on a server. I don't want to run 'cmake -DCMAKE_INSTALL_PREFIX=...' to reconfigure each time I need to switch a destination and prefer to minimize extra typing on a command line. Therefore, in my CMakeLists, I have

 set(CMAKE_INSTALL_PREFIX ${CMAKE_CURRENT_SOURCE_DIR}/../../_install)

Now, I am trying to use 'add_custom_target' but not sure how to do this correctly:

add_custom_target(DEPLOY
    COMMAND "${CMAKE_COMMAND}" --build . --target install --install ${SITE}
    WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
)

Any idea?

1 Answers

Here's a full example:

cmake_minimum_required(VERSION 3.21)
project(test)

set(SITE "${CMAKE_SOURCE_DIR}/_deploy"
    CACHE PATH "Alternate install prefix for 'deploy'")

add_executable(main main.cpp)

include(GNUInstallDirs)
install(TARGETS main)

add_custom_target(
  deploy
  COMMAND "${CMAKE_COMMAND}"
          --install "${CMAKE_BINARY_DIR}"
          --config  "$<CONFIG>"
          --prefix  "${SITE}"
)

Which reduces to

cmake --build /path/to/build --config ... --target deploy

Be warned that none of this will work if your install rules store the value of ${CMAKE_INSTALL_PREFIX}. You have to be careful to use relative paths only. If you do make this mistake, you'll have no choice but to fix your code or reconfigure.

Related