Finally, let us consider the installation directives. We need to install an executable, one library, and one header file. Executables and libraries are build targets, so we use the TARGETS option to the install command. Install rules for multiple targets can be set at once: CMake is aware of what kind of targets they are; that is, whether they are executables, shared libraries, or static libraries:
install(
TARGETS
message-shared
hello-world_wDSO
Executables will be installed inĀ RUNTIME DESTINATION, which we set to ${INSTALL_BINDIR}. Shared libraries are installed to LIBRARY DESTINATION, which we set to ${INSTALL_LIBDIR}. Static libraries would be installed to ARCHIVE DESTINATION, which we also set to ${INSTALL_LIBDIR}:
ARCHIVE
DESTINATION ${INSTALL_LIBDIR}
COMPONENT lib
RUNTIME
DESTINATION ${INSTALL_BINDIR}
COMPONENT bin
LIBRARY
DESTINATION ${INSTALL_LIBDIR}
COMPONENT lib
Note that we not only specified DESTINATION, but also COMPONENT. When installing the project with the cmake --build . --target installĀ command, all components were installed, as expected. However, it might be sometimes desirable to only install some of them. This is what the COMPONENT keyword can help us with. For example, to only install libraries, we can run the following:
$ cmake -D COMPONENT=lib -P cmake_install.cmake
Since the Message.hpp header file was set as a public header of the project, we can use the PUBLIC_HEADER keyword to install it along the other targets to the chosen destination: ${INSTALL_INCLUDEDIR}/message. Users of the library can now include the header with: #include <message/Message.hpp>, provided the proper location is passed to the compiler with the -I option.
The various destinations in the installation directives are interpreted as relative paths, unless an absolute path is used. But relative to what? There are different ways in which CMake can compute the absolute path, depending on what tool is triggering the installation. When using cmake --build . --target install, as we have done, paths will be computed relative to CMAKE_INSTALL_PREFIX. However, when using CPack, absolute paths will be computed relative to CPACK_PACKAGING_INSTALL_PREFIX. Usage of CPack will be shown in Chapter 11, Packaging Projects, Recipe 1, Generating source and binary packages.