Published:

Jarle Aase

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:

 1install(TARGETS targets... [EXPORT <export-name>]
 2        [[ARCHIVE|LIBRARY|RUNTIME|FRAMEWORK|BUNDLE|
 3          PRIVATE_HEADER|PUBLIC_HEADER|RESOURCE]
 4         [DESTINATION <dir>]
 5         [PERMISSIONS permissions...]
 6         [CONFIGURATIONS [Debug|Release|...]]
 7         [COMPONENT <component>]
 8         [OPTIONAL] [EXCLUDE_FROM_ALL]
 9         [NAMELINK_ONLY|NAMELINK_SKIP]
10        ] [...]
11        [INCLUDES DESTINATION [<dir> ...]]
12        )

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:

1install(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:

1project (stbl)
2
3add_executable(stbl main.cpp)
4
5install(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?)

1mkdir release
2cd release
3cmake -DCMAKE_BUILD_TYPE=Release ..
4make

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

1jgaa@vendetta:~/src/stbl/release$ sudo make install
2[sudo] password for jgaa:
3[ 85%] Built target libstbl
4[100%] Built target stbl
5Install the project...
6-- Install configuration: "Release"
7-- 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.