- Installing CMake
- Windows
- Linux, macOS, UNIX
- CMake — создание динамических библиотек
- Введение
- Динамические библиотеки. Теория
- Динамические библиотеки. Практика
- CMake adding libraries for Windows/Linux
- 3 Answers 3
- Введение в CMake
- Пример 1. Hello, World:
- Пример 2. Библиотеки:
- Пример 3. Подпроекты:
- Пример 4. Поиск библиотек:
- Пример 5. Внешние библиотеки и объектные файлы:
- Генераторы:
- Заключение:
- installВ¶
- SynopsisВ¶
- IntroductionВ¶
- Installing TargetsВ¶
- Installing DirectoriesВ¶
- Custom Installation LogicВ¶
- Installing ExportsВ¶
- Generated Installation ScriptВ¶
Installing CMake
There are several ways to install CMake, depending on your platform.
Windows
There are pre-compiled binaries available on the Download page for Windows as MSI packages and ZIP files. One may alternatively download and build CMake from source. The Download page also provides source releases. In order to build CMake from a source tree on Windows, you must first install the latest binary version of CMake because it is used for building the source tree. Once the binary is installed, run it on CMake as you would any other project. Typically this means selecting CMake as the Source directory and then selecting a binary directory for the resulting executables.
Linux, macOS, UNIX
There are pre-compiled binaries available on the Download page for some UNIX platforms. One may alternatively download and build CMake from source. The Download page provides source releases. There are two possible approaches for building CMake from a source tree. If there is no existing CMake installation, a bootstrap script is provided:
(Note: the make install step is optional, cmake will run from the build directory.)
By default bootstrap will build CMake without any debug or optimization flags. To enable optimizations you will need to specify the CMAKE_BUILD_TYPE option to bootstrap like this: ./bootstrap — -DCMAKE_BUILD_TYPE:STRING=Release
For more options with bootstrap, run ./bootstrap —help .
Or, an existing CMake installation can be used to build a new version:
(Note: the make install step is optional, cmake will run from the build directory.) If you are not using the GNU C++ compiler, you need to tell the bootstrap script (or cmake) which compiler you want to use. This is done by setting the environment variables CC and CXX before running it. For example:
CMake — создание динамических библиотек
Введение
CMake (от англ. cross platform make) — это кроссплатформенная система автоматизации сборки программного обеспечения из исходного кода.
CMake не занимается непосредственно сборкой, a лишь генерирует файлы управления сборкой из файлов CMakeLists.txt.
Динамические библиотеки. Теория
Создание динамических библиотек со статической линковкой в ОС Windows отличается от ОС GNU/Linux.
На ОС Windows для этого требуется связка .dll (dynamic link library) + .lib (library) файлов.
На ОС GNU/Linux для этого нужен всего лишь один .so (shared object) файл.
Динамические библиотеки. Практика
На практике хочется писать удобный, одинаковый код на обеих ОС.
В каждом проекте (или на несколько проектов одна) присутствовала условная компиляция:
Соответственно, для каждого экспортируемого класса из библиотеки необходимо прописать данный макрос:
В данном случае, на ОС Windows экспортируются все классы/методы, которые помечены данным макросом, а на ОС GNU/Linux, по умолчанию, всё экспортируется, т.к. нет макроса для скрытия классов/методов.
С выходом CMake версии 3.4.0, стало возможным создание библиотек с классами, которые экспортируются по умолчанию. Для этого в каждой цели (target), которые объявлены как SHARED (динамическая библиотека), необходимо включить свойство:
Пример небольшой библиотеки:
И убрать определение и использование макросов из кода:
Данное свойство автоматически создает module definition (.def) со всеми глобальными символами из .obj файла для динамической библиотеки на ОС Windows.
Далее данный файл (.def) передается компоновщику для создания .lib файла. На выходе на ОС Windows получается связка .lib + .dll
CMake adding libraries for Windows/Linux
Visual Studio C++ 2008 / GCC 4.4.2
I have written a program to run on Linux and now I have to port my code to run on Windows. I have decided to use CMake as I want to keep the same build system for both platforms.
However, I need to link with some libraries for both platforms. In my CMakeLists.txt I have the following:
However, when I compile on Visual Studio I get the following error:
What can I do to resolve this problem?
========= Edit In the top level directory
In the subdirectory of client I have this CMakeLists.txt
And in the subdirectory of test_clt where I create and link my executable.
3 Answers 3
You need to use the Target Link Libraries command. The target would be the executable you’re building.
EDIT: You shouldn’t specify the libs you’re linking against in C_FLAGS. You can do something like TARGET_LINK_LIBRARIES(execName, ws_32, . ). I’m not 100% sure if you need the .lib. Been a while since I used CMake.
Disclaimer: My answer is of philosophical nature which should encourage you to avoid touching CMAKE_C_FLAGS directly. For the direct answer that just solves your problem look what Bill ( the lead architect of the CMake btw. ) wrote.
The thing about CMake is, that it lets you describe what you want to do without referring to a specific compiler or platform. What CMake does is building the compiler and linker flags from your usage of
- include_directories
- add_definitions
- add_library
- add_executable
- target_link_libraries
If there are no external dependencies, other than the compiler itself, this is all you need. For external dependencies use find_package It defines a set of variables, like
for usage with respectively include_directories and target_link_libraries. CMake ships with a bunch of so called module files, like FindSDL.cmake and many others can be googled.
The next lower level is to use
which are used in the Find. cmake modules itself.
The CMAKE_C_FLAGS variable is composed by CMake from these commands. Modifying it means you bypass CMake. There are cases, like for special optimization flags, you want to do this, but at this point all power and thus responsibility transfered from CMake to you.
Введение в CMake
CMake — кроcсплатформенная утилита для автоматической сборки программы из исходного кода. При этом сама CMake непосредственно сборкой не занимается, а представляет из себя front-end. В качестве back-end`a могут выступать различные версии make и Ninja. Так же CMake позволяет создавать проекты для CodeBlocks, Eclipse, KDevelop3, MS VC++ и Xcode. Стоит отметить, что большинство проектов создаются не нативных, а всё с теми же back-end`ами.
Для того что бы собрать проект средствами CMake, необходимо в корне дерева исходников разместить файл CMakeLists.txt, хранящий правила и цели сборки, и произвести несколько простых шагов.
Разберёмся на примерах.
Пример 1. Hello, World:
Синтаксис CMake похож на синтаксис bash, всё что после символа «#» является комментарием и обрабатываться программой не будет. CMake позволяет не засорять дерево исходных кодов временными файлами — очень просто и без лишних телодвижений сборка производится «Out-of-Source».
Создадим пустую директорию для временных файлов и перейдём туда.
$ mkdir tmp
fshp@panica-desktop:
$ cd tmp/
fshp@panica-desktop:
/cmake/example_1/
…
— Build files have been written to: /home/fshp/tmp
fshp@panica-desktop:
/tmp$ ls
CMakeCache.txt CMakeFiles cmake_install.cmake Makefile
fshp@panica-desktop:
/tmp$ make
Scanning dependencies of target main
[100%] Building CXX object CMakeFiles/main.dir/main.cpp.o
Linking CXX executable main
[100%] Built target main
fshp@panica-desktop:
/tmp$ ./main
Hello, World!
fshp@panica-desktop:
Итак, наша программа собралась.
Папку tmp можно очищать\удалять без риска поломать исходники. Если CMakeLists.txt был изменен, то вызов make автоматически запустит cmake. Если исходники были перемещены, то нужно очистить временную директорию и запустить cmake вручную.
Пример 2. Библиотеки:
Переменные могут хранить списки значений, разделённых пробелами\табуляциями\переносами:
Оба варианта правильные
Что бы получить значение переменной ипользуем конструкцию:
Итак, эта версия нашего проекта включает в себя одну статическую библиотеку, собираемую из исходников. Если заменить «STATIC» на «SHARED», то получим библиотеку динамическую. Если тип библиотеки не указать, по умолчанию она соберётся как статическая.
При линковке указываются все необходимые библиотеки:
Как и при ручной компиляции, имена библиотек указываются без стандартного префикса «lib».
Итак, сборка библиотек с CMake не вызывает проблем, при этом тип библиотеки статическая\динамическая меняется лишь одним параметром.
Пример 3. Подпроекты:
В файле подпроекта ничего нового для вас нет. А вот в основном файле новые команды:
main.cpp мы не меняли, а foo.h перенесли. Команда указывает компилятору, где искать заголовочные файлы. Может быть вызвана несколько раз. Хидеры будут искаться во всех указаных директориях.
Указываем директорию с подпроектом, который будет собран как самостоятельный.
Вывод: проекты на CMake можно объединять в довольно сложные иерархические структуры, причем каждый подпроект в реальности является самостоятельным проектом, который в свою очередь может сам состоять из подпроектов. Это позволяет легко разбить вашу программу на необходимое количество отдельных модулей. Примером такого подхода может служить KDE.
Пример 4. Поиск библиотек:
CMake обладает достаточно развитыми средствами поиска установленых библиотек, правда они не встроеные, а реализованы в виде отдельных модулей. В стандартной поставке довольно много модулей, но некоторые проекты (например Ogre) поставляют свои. Они позволяют системе автоматически определить наличие необходимых для линковки проекта библиотек.
На debian модули располагаются в /usr/share/cmake-2.8/Modules/ (у вас версия может отличаться). За поиск библиотек отвечают модули, называющиеся FindNAME.cmake, где NAME — имя библиотеки.
Думаю, смысл должен быть понятен. Первый и второй блок — поиск библиотеки. Если в системе её нет, выведется сообщение об ошибке и завершается выполнение cmake. Третий блок похож, только он ищет не целый пакет библиотек, а лишь необходимый компонент. Каждый такой автоматизированый поиск определяет после выполнения как минимум 3 переменные:
SDL_FOUND, LIBXML2_FOUND, Boost_FOUND — признак присутствия бибилиотеки;
SDL_LIBRARY, LIBXML2_LIBRARIES, Boost_LIBRARIES — имена библиотек для линковки;
SDL_INCLUDE_DIR, LIBXML2_INCLUDE_DIR, Boost_INCLUDE_DIRS — пути к заголовочным файлам.
Если с первыми более или менее понятно, то вторые и третьи мне доставили много хлопот — половина имеет имена в единственном числе, половина — во множественном. Но оказалось, это легко отследить. В каждом модуле вначале есть коментарии, там описаны определяемые переменные. Посмотрите, например, /usr/share/cmake-2.8/Modules/FindLibXml2.cmake
Как видите, CMake способен сам определить наличие и местоположение необходимых библиотек и заголовочных файлов. В принципе, это должна уметь любая система автоматической сборки, иначе смысл в ней?
Пример 5. Внешние библиотеки и объектные файлы:
Если вы пишите для «дяди», а злой «дядя» любит самописные библиотеки и делиться исходниками не желает, поэтому присылает готовую библиотеку, то вы по адресу.
Объектные файлы в CMake стоят на ряду с исходниками — достаточно включить объектник в список файлов для компиляции.
С библиотеками потуже. Как известно, статическая библиотека это не что иное, как ar-архив, внутри которого лежат обычные объектники, никак не связаные между собой. Вы, наверное, уже догадались, как я поступал сначала. Да, просто потрошил библиотеку. Но потом был найден способ поэлегантнее:
Слово «IMPORTED», указывает, что библиотека берётся извне.
В CMake каждая цель имеет параметры, а set_property позволяет их изменять.
Линкуется такая библиотека стандартно:
Для динамических библиотек все аналогично, только тип «SHARED», расширение — «.so».
К сожалению, поддержка несистемных библиотек реализована немного костыльно. Возможно, я просто не знаю правильного варианта, поэтому буду рад, если «ткнете мордочкой». С другой стороны это не навороченый экзоскелет с системой жизнеобеспечения, а простейший костыль из двух строк.
Генераторы:
/cmake/example_3/ -G «KDevelop3 — Unix Makefiles»
Заключение:
Это не перевод мануала, а результат использования CMake в одном коммерческом проекте. Буду рад, если статья поможет хотя бы одному человеку — на русском языке подобной документации довольно мало.
Чем понравился CMake лично мне:
- один проект — один файл. Не нужно хранить кучу скриптов настройки, сборки и прочего хлама;
- Скорость работы в сравнении с autotools;
- простой и понятный синтаксис, конечно с элегантностью питона не потягаться, но и не брейнфак, в конце концов.;
- является front-end`ом для множества IDE;
- отображение прогресса — довольно удобно;
- цветной вывод — в серые будни немного краски не помешает;
Для Sublime Text есть плагин, добавляющий подсветку синтаксиса CMake, он так и называется — «CMake».
Примеры
installВ¶
Specify rules to run at install time.
SynopsisВ¶
IntroductionВ¶
This command generates installation rules for a project. Install rules specified by calls to the install() command within a source directory are executed in order during installation.
Changed in version 3.14: Install rules in subdirectories added by calls to the add_subdirectory() command are interleaved with those in the parent directory to run in the order declared (see policy CMP0082 ).
There are multiple signatures for this command. Some of them define installation options for files and targets. Options common to multiple signatures are covered here but they are valid only for signatures that specify them. The common options are:
Specify the directory on disk to which a file will be installed. Arguments can be relative or absolute paths.
If a relative path is given it is interpreted relative to the value of the CMAKE_INSTALL_PREFIX variable. The prefix can be relocated at install time using the DESTDIR mechanism explained in the CMAKE_INSTALL_PREFIX variable documentation.
If an absolute path (with a leading slash or drive letter) is given it is used verbatim.
As absolute paths are not supported by cpack installer generators, it is preferable to use relative paths throughout. In particular, there is no need to make paths absolute by prepending CMAKE_INSTALL_PREFIX ; this prefix is used by default if the DESTINATION is a relative path.
Specify permissions for installed files. Valid permissions are OWNER_READ , OWNER_WRITE , OWNER_EXECUTE , GROUP_READ , GROUP_WRITE , GROUP_EXECUTE , WORLD_READ , WORLD_WRITE , WORLD_EXECUTE , SETUID , and SETGID . Permissions that do not make sense on certain platforms are ignored on those platforms.
Specify a list of build configurations for which the install rule applies (Debug, Release, etc.). Note that the values specified for this option only apply to options listed AFTER the CONFIGURATIONS option. For example, to set separate install paths for the Debug and Release configurations, do the following:
Note that CONFIGURATIONS appears BEFORE RUNTIME DESTINATION .
Specify an installation component name with which the install rule is associated, such as «runtime» or «development». During component-specific installation only install rules associated with the given component name will be executed. During a full installation all components are installed unless marked with EXCLUDE_FROM_ALL . If COMPONENT is not provided a default component «Unspecified» is created. The default component name may be controlled with the CMAKE_INSTALL_DEFAULT_COMPONENT_NAME variable.
New in version 3.6.
Specify that the file is excluded from a full installation and only installed as part of a component-specific installation
Specify a name for an installed file that may be different from the original file. Renaming is allowed only when a single file is installed by the command.
Specify that it is not an error if the file to be installed does not exist.
New in version 3.1: Command signatures that install files may print messages during installation. Use the CMAKE_INSTALL_MESSAGE variable to control which messages are printed.
New in version 3.11: Many of the install() variants implicitly create the directories containing the installed files. If CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS is set, these directories will be created with the permissions specified. Otherwise, they will be created according to the uname rules on Unix-like platforms. Windows platforms are unaffected.
Installing TargetsВ¶
The TARGETS form specifies rules for installing targets from a project. There are several kinds of target Output Artifacts that may be installed:
Target artifacts of this kind include:
Static libraries (except on macOS when marked as FRAMEWORK , see below);
DLL import libraries (on all Windows-based systems including Cygwin; they have extension .lib , in contrast to the .dll libraries that go to RUNTIME );
On AIX, the linker import file created for executables with ENABLE_EXPORTS enabled.
Target artifacts of this kind include:
Shared libraries, except
DLLs (these go to RUNTIME , see below),
on macOS when marked as FRAMEWORK (see below).
Target artifacts of this kind include:
Executables (except on macOS when marked as MACOSX_BUNDLE , see BUNDLE below);
DLLs (on all Windows-based systems including Cygwin; note that the accompanying import libraries are of kind ARCHIVE ).
New in version 3.9.
Object files associated with object libraries.
Both static and shared libraries marked with the FRAMEWORK property are treated as FRAMEWORK targets on macOS.
Executables marked with the MACOSX_BUNDLE property are treated as BUNDLE targets on macOS.
Any PUBLIC_HEADER files associated with a library are installed in the destination specified by the PUBLIC_HEADER argument on non-Apple platforms. Rules defined by this argument are ignored for FRAMEWORK libraries on Apple platforms because the associated files are installed into the appropriate locations inside the framework folder. See PUBLIC_HEADER for details.
Similar to PUBLIC_HEADER , but for PRIVATE_HEADER files. See PRIVATE_HEADER for details.
Similar to PUBLIC_HEADER and PRIVATE_HEADER , but for RESOURCE files. See RESOURCE for details.
For each of these arguments given, the arguments following them only apply to the target or file type specified in the argument. If none is given, the installation properties apply to all target types. If only one is given then only targets of that type will be installed (which can be used to install just a DLL or just an import library.)
For regular executables, static libraries and shared libraries, the DESTINATION argument is not required. For these target types, when DESTINATION is omitted, a default destination will be taken from the appropriate variable from GNUInstallDirs , or set to a built-in default value if that variable is not defined. The same is true for the public and private headers associated with the installed targets through the PUBLIC_HEADER and PRIVATE_HEADER target properties. A destination must always be provided for module libraries, Apple bundles and frameworks. A destination can be omitted for interface and object libraries, but they are handled differently (see the discussion of this topic toward the end of this section).
The following table shows the target types with their associated variables and built-in defaults that apply when no destination is given:
Projects wishing to follow the common practice of installing headers into a project-specific subdirectory will need to provide a destination rather than rely on the above.
To make packages compliant with distribution filesystem layout policies, if projects must specify a DESTINATION , it is recommended that they use a path that begins with the appropriate GNUInstallDirs variable. This allows package maintainers to control the install destination by setting the appropriate cache variables. The following example shows a static library being installed to the default destination provided by GNUInstallDirs , but with its headers installed to a project-specific subdirectory that follows the above recommendation:
In addition to the common options listed above, each target can accept the following additional arguments:
New in version 3.12.
On some platforms a versioned shared library has a symbolic link such as:
where lib .so.1 is the soname of the library and lib .so is a «namelink» allowing linkers to find the library when given -l . The NAMELINK_COMPONENT option is similar to the COMPONENT option, but it changes the installation component of a shared library namelink if one is generated. If not specified, this defaults to the value of COMPONENT . It is an error to use this parameter outside of a LIBRARY block.
Consider the following example:
In this scenario, if you choose to install only the Development component, both the headers and namelink will be installed without the library. (If you don’t also install the Libraries component, the namelink will be a dangling symlink, and projects that link to the library will have build errors.) If you install only the Libraries component, only the library will be installed, without the headers and namelink.
This option is typically used for package managers that have separate runtime and development packages. For example, on Debian systems, the library is expected to be in the runtime package, and the headers and namelink are expected to be in the development package.
See the VERSION and SOVERSION target properties for details on creating versioned shared libraries.
This option causes the installation of only the namelink when a library target is installed. On platforms where versioned shared libraries do not have namelinks or when a library is not versioned, the NAMELINK_ONLY option installs nothing. It is an error to use this parameter outside of a LIBRARY block.
When NAMELINK_ONLY is given, either NAMELINK_COMPONENT or COMPONENT may be used to specify the installation component of the namelink, but COMPONENT should generally be preferred.
Similar to NAMELINK_ONLY , but it has the opposite effect: it causes the installation of library files other than the namelink when a library target is installed. When neither NAMELINK_ONLY or NAMELINK_SKIP are given, both portions are installed. On platforms where versioned shared libraries do not have symlinks or when a library is not versioned, NAMELINK_SKIP installs the library. It is an error to use this parameter outside of a LIBRARY block.
If NAMELINK_SKIP is specified, NAMELINK_COMPONENT has no effect. It is not recommended to use NAMELINK_SKIP in conjunction with NAMELINK_COMPONENT .
The install(TARGETS) command can also accept the following options at the top level:
This option associates the installed target files with an export called . It must appear before any target options. To actually install the export file itself, call install(EXPORT), documented below. See documentation of the EXPORT_NAME target property to change the name of the exported target.
This option specifies a list of directories which will be added to the INTERFACE_INCLUDE_DIRECTORIES target property of the when exported by the install(EXPORT) command. If a relative path is specified, it is treated as relative to the $ .
One or more groups of properties may be specified in a single call to the TARGETS form of this command. A target may be installed more than once to different locations. Consider hypothetical targets myExe , mySharedLib , and myStaticLib . The code:
will install myExe to
The FILES form specifies rules for installing files for a project. File names given as relative paths are interpreted with respect to the current source directory. Files installed by this form are by default given permissions OWNER_WRITE , OWNER_READ , GROUP_READ , and WORLD_READ if no PERMISSIONS argument is given.
The PROGRAMS form is identical to the FILES form except that the default permissions for the installed file also include OWNER_EXECUTE , GROUP_EXECUTE , and WORLD_EXECUTE . This form is intended to install programs that are not targets, such as shell scripts. Use the TARGETS form to install targets built within the project.
The list of files. given to FILES or PROGRAMS may use «generator expressions» with the syntax $ . See the cmake-generator-expressions(7) manual for available expressions. However, if any item begins in a generator expression it must evaluate to a full path.
Either a TYPE or a DESTINATION must be provided, but not both. A TYPE argument specifies the generic file type of the files being installed. A destination will then be set automatically by taking the corresponding variable from GNUInstallDirs , or by using a built-in default if that variable is not defined. See the table below for the supported file types and their corresponding variables and built-in defaults. Projects can provide a DESTINATION argument instead of a file type if they wish to explicitly define the install destination.
Projects wishing to follow the common practice of installing headers into a project-specific subdirectory will need to provide a destination rather than rely on the above.
Note that some of the types’ built-in defaults use the DATAROOT directory as a prefix. The DATAROOT prefix is calculated similarly to the types, with CMAKE_INSTALL_DATAROOTDIR as the variable and share as the built-in default. You cannot use DATAROOT as a TYPE parameter; please use DATA instead.
To make packages compliant with distribution filesystem layout policies, if projects must specify a DESTINATION , it is recommended that they use a path that begins with the appropriate GNUInstallDirs variable. This allows package maintainers to control the install destination by setting the appropriate cache variables. The following example shows how to follow this advice while installing headers to a project-specific subdirectory:
New in version 3.4: An install destination given as a DESTINATION argument may use «generator expressions» with the syntax $ . See the cmake-generator-expressions(7) manual for available expressions.
New in version 3.20: An install rename given as a RENAME argument may use «generator expressions» with the syntax $ . See the cmake-generator-expressions(7) manual for available expressions.
Installing DirectoriesВ¶
The DIRECTORY form installs contents of one or more directories to a given destination. The directory structure is copied verbatim to the destination. The last component of each directory name is appended to the destination directory but a trailing slash may be used to avoid this because it leaves the last component empty. Directory names given as relative paths are interpreted with respect to the current source directory. If no input directory names are given the destination directory will be created but nothing will be installed into it. The FILE_PERMISSIONS and DIRECTORY_PERMISSIONS options specify permissions given to files and directories in the destination. If USE_SOURCE_PERMISSIONS is specified and FILE_PERMISSIONS is not, file permissions will be copied from the source directory structure. If no permissions are specified files will be given the default permissions specified in the FILES form of the command, and the directories will be given the default permissions specified in the PROGRAMS form of the command.
New in version 3.1: The MESSAGE_NEVER option disables file installation status output.
Installation of directories may be controlled with fine granularity using the PATTERN or REGEX options. These «match» options specify a globbing pattern or regular expression to match directories or files encountered within input directories. They may be used to apply certain options (see below) to a subset of the files and directories encountered. The full path to each input file or directory (with forward slashes) is matched against the expression. A PATTERN will match only complete file names: the portion of the full path matching the pattern must occur at the end of the file name and be preceded by a slash. A REGEX will match any portion of the full path but it may use / and $ to simulate the PATTERN behavior. By default all files and directories are installed whether or not they are matched. The FILES_MATCHING option may be given before the first match option to disable installation of files (but not directories) not matched by any expression. For example, the code
will extract and install header files from a source tree.
Some options may follow a PATTERN or REGEX expression and are applied only to files or directories matching them. The EXCLUDE option will skip the matched file or directory. The PERMISSIONS option overrides the permissions setting for the matched file or directory. For example the code
will install the icons directory to share/myproj/icons and the scripts directory to share/myproj . The icons will get default file permissions, the scripts will be given specific permissions, and any CVS directories will be excluded.
Either a TYPE or a DESTINATION must be provided, but not both. A TYPE argument specifies the generic file type of the files within the listed directories being installed. A destination will then be set automatically by taking the corresponding variable from GNUInstallDirs , or by using a built-in default if that variable is not defined. See the table below for the supported file types and their corresponding variables and built-in defaults. Projects can provide a DESTINATION argument instead of a file type if they wish to explicitly define the install destination.
Note that some of the types’ built-in defaults use the DATAROOT directory as a prefix. The DATAROOT prefix is calculated similarly to the types, with CMAKE_INSTALL_DATAROOTDIR as the variable and share as the built-in default. You cannot use DATAROOT as a TYPE parameter; please use DATA instead.
To make packages compliant with distribution filesystem layout policies, if projects must specify a DESTINATION , it is recommended that they use a path that begins with the appropriate GNUInstallDirs variable. This allows package maintainers to control the install destination by setting the appropriate cache variables.
New in version 3.4: An install destination given as a DESTINATION argument may use «generator expressions» with the syntax $ . See the cmake-generator-expressions(7) manual for available expressions.
New in version 3.5: The list of dirs. given to DIRECTORY may use «generator expressions» too.
Custom Installation LogicВ¶
The SCRIPT form will invoke the given CMake script files during installation. If the script file name is a relative path it will be interpreted with respect to the current source directory. The CODE form will invoke the given CMake code during installation. Code is specified as a single argument inside a double-quoted string. For example, the code
will print a message during installation.
New in version 3.14: or may use «generator expressions» with the syntax $ (in the case of , this refers to their use in the file name, not the file’s contents). See the cmake-generator-expressions(7) manual for available expressions.
Installing ExportsВ¶
The EXPORT form generates and installs a CMake file containing code to import targets from the installation tree into another project. Target installations are associated with the export using the EXPORT option of the install(TARGETS) signature documented above. The NAMESPACE option will prepend to the target names as they are written to the import file. By default the generated file will be called .cmake but the FILE option may be used to specify a different name. The value given to the FILE option must be a file name with the .cmake extension. If a CONFIGURATIONS option is given then the file will only be installed when one of the named configurations is installed. Additionally, the generated import file will reference only the matching target configurations. The EXPORT_LINK_INTERFACE_LIBRARIES keyword, if present, causes the contents of the properties matching (IMPORTED_)?LINK_INTERFACE_LIBRARIES(_ )? to be exported, when policy CMP0022 is NEW .
The installed .cmake file may come with additional per-configuration -*.cmake files to be loaded by globbing. Do not use an export name that is the same as the package name in combination with installing a
-config.cmake file or the latter may be incorrectly matched by the glob and loaded.
When a COMPONENT option is given, the listed implicitly depends on all components mentioned in the export set. The exported .cmake file will require each of the exported components to be present in order for dependent projects to build properly. For example, a project may define components Runtime and Development , with shared libraries going into the Runtime component and static libraries and headers going into the Development component. The export set would also typically be part of the Development component, but it would export targets from both the Runtime and Development components. Therefore, the Runtime component would need to be installed if the Development component was installed, but not vice versa. If the Development component was installed without the Runtime component, dependent projects that try to link against it would have build errors. Package managers, such as APT and RPM, typically handle this by listing the Runtime component as a dependency of the Development component in the package metadata, ensuring that the library is always installed if the headers and CMake export file are present.
New in version 3.7: In addition to cmake language files, the EXPORT_ANDROID_MK mode maybe used to specify an export to the android ndk build system. This mode accepts the same options as the normal export mode. The Android NDK supports the use of prebuilt libraries, both static and shared. This allows cmake to build the libraries of a project and make them available to an ndk build system complete with transitive dependencies, include flags and defines required to use the libraries.
The EXPORT form is useful to help outside projects use targets built and installed by the current project. For example, the code
will install the executable myexe to
/bin and code to import it in the file
/share/ndk-modules/Android.mk . An outside project may load this file with the include command and reference the myexe executable from the installation tree using the imported target name mp_myexe as if the target were built in its own tree.
This command supercedes the install_targets() command and the PRE_INSTALL_SCRIPT and POST_INSTALL_SCRIPT target properties. It also replaces the FILES forms of the install_files() and install_programs() commands. The processing order of these install rules relative to those generated by install_targets() , install_files() , and install_programs() commands is not defined.
Generated Installation ScriptВ¶
Use of this feature is not recommended. Please consider using the —install argument of cmake(1) instead.
The install() command generates a file, cmake_install.cmake , inside the build directory, which is used internally by the generated install target and by CPack. You can also invoke this script manually with cmake -P . This script accepts several variables:
Set this variable to install only a single CPack component as opposed to all of them. For example, if you only want to install the Development component, run cmake -DCOMPONENT=Development -P cmake_install.cmake .
Set this variable to change the build type if you are using a multi-config generator. For example, to install with the Debug configuration, run cmake -DBUILD_TYPE=Debug -P cmake_install.cmake .
This is an environment variable rather than a CMake variable. It allows you to change the installation prefix on UNIX systems. See DESTDIR for details.