CMake Recipe #1: Append version number to the install path

132

In some situations, it’s necessary to keep older versions of a program along with the newer.  Here is a recipe for appending the version number to your install path:

PROJECT(MyProg C) 
SET (VERSION "0.1.4") 
... 
IF(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
SET(CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}-${VERSION}" 
CACHE STRING "Install path" FORCE)
ENDIF() 
... 
# and if you use CPack, just default the installer to the right path using:
set(CPACK_PACKAGE_INSTALL_DIRECTORY "MyProg-${VERSION}") 
 

The CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT is necessary here because if it’s missing, the path becomes recursive and will continue to append ${PROJECT_NAME}-${VERSION} to the path infinitely.  The conditional ensures that it only does this once.