Published:

Adding an install target in CMake

bookmark 1 min read

CMake can do more than just build your software projects. It can also install them.

CMake comes with extensive documentation, and few or no examples on how to use the different options. For example, the install statement reads like:

install(TARGETS targets... [EXPORT <export-name>]
        [[ARCHIVE|LIBRARY|RUNTIME|FRAMEWORK|BUNDLE|
          PRIVATE_HEADER|PUBLIC_HEADER|RESOURCE]
         [DESTINATION <dir>]
         [PERMISSIONS permissions...]
         [CONFIGURATIONS [Debug|Release|...]]
         [COMPONENT <component>]
         [OPTIONAL] [EXCLUDE_FROM_ALL]
         [NAMELINK_ONLY|NAMELINK_SKIP]
        ] [...]
        [INCLUDES DESTINATION [<dir> ...]]
        )

Right...! Extensive, and far from obvious.

So - how do you make cmake install your beautiful little command-line program? It's actual quite simple.

Just after the add_executable blah blah statement, where you declare what you want to build, and how, add the one-liner install statement. This example show how to install the binary for my static blog generator:

install(TARGETS stbl DESTINATION bin)

This may be in the root CMakeLists.txt file, or in a CMakeLists.txt file in a source directory where you keep your sources.

Simplified example from stbl:

project (stbl)

add_executable(stbl main.cpp)

install(TARGETS stbl DESTINATION bin)

If you don't do anything, cmake will now create an install target for your build. From the Linux command-line, it works like this:

Make a release build (you probably don't want to install debug binaries - right?)

mkdir release
cd release
cmake -DCMAKE_BUILD_TYPE=Release ..
make

Then, install your beautiful program on the local machine. (Here I show the full output from the command):

jgaa@vendetta:~/src/stbl/release$ sudo make install
[sudo] password for jgaa:
[ 85%] Built target libstbl
[100%] Built target stbl
Install the project...
-- Install configuration: "Release"
-- Installing: /usr/local/bin/stbl

Note that even though we just specified bin in the install statement, the program is correctly installed in /usr/local/bin. That's because CMake keep a sane install destination in it's CMAKE_INSTALL_PREFIX variable.

Nice.