Меню Рубрики

Cmake install cmake windows

cmake Начало работы с cmake

замечания

CMake — это инструмент для определения и управления сборками кода, прежде всего для C ++.

CMake — это кросс-платформенный инструмент; идея состоит в том, чтобы иметь единое определение того, как строится проект, — который переводится в конкретные определения построения для любой поддерживаемой платформы.

Это достигается путем сопряжения с различными платформами, специфичными для платформы; CMake — это промежуточный шаг, который генерирует ввод данных для разных конкретных платформ. В Linux CMake генерирует Makefiles; в Windows он может создавать проекты Visual Studio и т. д.

Поведение сборки определяется в файлах CMakeLists.txt — по одному в каждом каталоге исходного кода. Файл CMakeLists каждого каталога определяет, что должна делать система сборки в этом конкретном каталоге. Он также определяет, какие подкаталоги должны обрабатывать CMake.

Типичные действия включают:

  • Создайте библиотеку или исполняемый файл из некоторых исходных файлов в этом каталоге.
  • Добавьте путь к пути include-path, который используется во время сборки.
  • Определите переменные, которые будет использовать buildsystem в этом каталоге, и в его подкаталогах.
  • Создайте файл на основе конкретной конфигурации сборки.
  • Найдите библиотеку, которая находится где-то в исходном дереве.

Окончательные файлы CMakeLists могут быть очень четкими и понятными, поскольку каждый из них настолько ограничен по объему. Каждый из них обрабатывает столько же сборки, сколько присутствует в текущем каталоге.

Для официальных ресурсов на CMake см. Документацию и учебник CMake.

Версии

Версия Дата выхода
3,9 2017-07-18
3,8 2017-04-10
3,7 2016-11-11
3,6 2016-07-07
3,5 2016-03-08
3,4 2015-11-12
3,3 2015-07-23
3,2 2015-03-10
3,1 2014-12-17
3.0 2014-06-10
2.8.12.1 2013-11-08
2.8.12 2013-10-11
2.8.11 2013-05-16
2.8.10.2 2012-11-27
2.8.10.1 2012-11-07
2.8.10 2012-10-31
2.8.9 2012-08-09
2.8.8 2012-04-18
2.8.7 2011-12-30
2.8.6 2011-12-30
2.8.5 2011-07-08
2.8.4 2011-02-16
2.8.3 2010-11-03
2.8.2 2010-06-28
2.8.1 2010-03-17
2,8 2009-11-13
2,6 2008-05-05

«Привет мир» в качестве библиотеки

В этом примере показано, как развернуть программу «Hello World» в качестве библиотеки и как связать ее с другими объектами.

Скажем, у нас есть тот же набор исходных / заголовочных файлов, что и в примере http://www.riptutorial.com/cmake/example/22391/-hello-world—with-multiple-source-files . Вместо создания из нескольких исходных файлов мы можем сначала развернуть foo.cpp как библиотеку с помощью add_library() а затем связать ее с основной программой с помощью target_link_libraries() .

Мы модифицируем CMakeLists.txt для

и после тех же шагов мы получим тот же результат.

«Hello World» с несколькими исходными файлами

Сначала мы можем указать каталоги файлов заголовков include_directories() , тогда нам нужно указать соответствующие исходные файлы целевого исполняемого файла с помощью add_executable() и убедиться, что в исходных файлах есть только одна функция main() .

Ниже приведен простой пример: все файлы предполагаются помещенными в каталог PROJECT_SOURCE_DIR .

main.cpp

foo.h

foo.cpp

CMakeLists.txt

Мы можем следовать той же процедуре в приведенном выше примере, чтобы построить наш проект. Затем выполнение app распечатает

Установка CMake

Перейдите на страницу загрузки CMake и получите двоичный файл для вашей операционной системы, например Windows, Linux или Mac OS X. В Windows дважды щелкните двоичный файл для установки. В Linux запускается двоичный файл с терминала.

В Linux вы также можете установить пакеты из диспетчера пакетов дистрибутива. На Ubuntu 16.04 вы можете установить командную строку и графическое приложение с помощью:

В FreeBSD вы можете установить командную строку и графическое приложение на основе Qt с помощью:

В Mac OSX, если вы используете один из менеджеров пакетов, доступных для установки вашего программного обеспечения, наиболее заметным из которых является MacPorts ( MacPorts ) и Homebrew ( Homebrew ), вы также можете установить CMake через один из них. Например, в случае MacPorts, введите следующие

установит CMake, в то время как в случае использования ящика Homebrew, который вы наберете

После того, как вы установили CMake, вы можете легко проверить, выполнив следующие

Вы должны увидеть что-то похожее на следующее

Простой проект «Hello World»

Учитывая исходный файл C ++ main.cpp определяющий функцию main() , сопровождающий файл CMakeLists.txt (со следующим содержимым) будет инструктировать CMake для генерации соответствующих инструкций сборки для текущей системы и компилятора C ++ по умолчанию.

CMakeLists.txt

cmake_minimum_required(VERSION 2.4) устанавливает минимальную версию CMake, необходимую для оценки текущего скрипта.

project(hello_world) запускает новый проект CMake. Это вызовет много внутренней логики CMake, особенно при обнаружении компилятора C и C ++ по умолчанию.

С помощью add_executable(app main.cpp) создается целевое app для сборки, которое будет вызывать сконфигурированный компилятор с некоторыми стандартными флагами для текущего параметра для компиляции исполняемого app из данного исходного файла main.cpp .

Командная строка (In-Source-Build, не рекомендуется)

cmake . обнаруживает компилятор, оценивает CMakeLists.txt в данном . и генерирует среду сборки в текущем рабочем каталоге.

cmake —build . команда является абстракцией для необходимого вызова build / make.

Командная строка (рекомендуется использовать Out-of-Source)

Чтобы ваш исходный код был чистым от каких-либо артефактов сборки, вы должны делать сборки «вне источника».

Или CMake также может абстрагировать основные команды оболочки платформы из примера выше:

Переключение между типами сборки, например отладка и выпуск

CMake знает несколько типов сборки, которые обычно влияют на параметры компилятора и компоновщика по умолчанию (такие как создаваемая отладочная информация) или альтернативные пути кода.

По умолчанию CMake может обрабатывать следующие типы сборки:

  • Отладка : обычно классическая сборка отладки, включая отладочную информацию, отсутствие оптимизации и т. Д.
  • Выпуск : типичная версия сборки без отладочной информации и полной оптимизации.
  • RelWithDebInfo:: То же, что и Release , но с информацией об отладке.
  • MinSizeRel : специальная версия выпуска, оптимизированная для размера.

Как обрабатываются конфигурации, зависит от используемого генератора.

Некоторые генераторы (например, Visual Studio) поддерживают несколько конфигураций. CMake будет генерировать все конфигурации сразу, и вы можете выбрать из IDE или использовать —config CONFIG (с cmake —build ), какую конфигурацию вы хотите построить. Для этих генераторов CMake будет стараться изо всех сил генерировать структуру каталогов сборки, чтобы файлы из разных конфигураций не наступали друг на друга.

Генераторы, которые поддерживают только одну конфигурацию (например, Unix Make-файлы), работают по-разному. Здесь CMAKE_BUILD_TYPE активная конфигурация определяется значением переменной CMake CMAKE_BUILD_TYPE .

Например, чтобы выбрать другой тип сборки, можно выполнить следующие команды командной строки:

Сценарий CMake должен избегать установки самого CMAKE_BUILD_TYPE , так как обычно это отвечает за ответственность пользователей.

Для генераторов с одним коннектором для переключения конфигурации требуется перезапуск CMake. Последующая сборка, скорее всего, перезапишет объектные файлы, созданные более ранней конфигурацией.

Источник

installВ¶

Specify rules to run at install time.

This command generates installation rules for a project. Rules specified by calls to this command within a source directory are executed in order during installation. The order across directories is not defined.

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:

DESTINATION Specify the directory on disk to which a file will be installed. If a full path (with a leading slash or drive letter) is given it is used directly. 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. PERMISSIONS 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. CONFIGURATIONS Specify a list of build configurations for which the install rule applies (Debug, Release, etc.). COMPONENT 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. 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. RENAME 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. OPTIONAL Specify that it is not an error if the file to be installed does not exist.

The TARGETS form specifies rules for installing targets from a project. There are five kinds of target files that may be installed: ARCHIVE , LIBRARY , RUNTIME , FRAMEWORK , and BUNDLE . Executables are treated as RUNTIME targets, except that those marked with the MACOSX_BUNDLE property are treated as BUNDLE targets on OS X. Static libraries are always treated as ARCHIVE targets. Module libraries are always treated as LIBRARY targets. For non-DLL platforms shared libraries are treated as LIBRARY targets, except that those marked with the FRAMEWORK property are treated as FRAMEWORK targets on OS X. For DLL platforms the DLL part of a shared library is treated as a RUNTIME target and the corresponding import library is treated as an ARCHIVE target. All Windows-based systems including Cygwin are DLL platforms. The ARCHIVE , LIBRARY , RUNTIME , and FRAMEWORK arguments change the type of target to which the subsequent properties apply. 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). The INCLUDES DESTINATION 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 $ .

The PRIVATE_HEADER , PUBLIC_HEADER , and RESOURCE arguments cause subsequent properties to be applied to installing a FRAMEWORK shared library target’s associated files on non-Apple platforms. Rules defined by these arguments are ignored on Apple platforms because the associated files are installed into the appropriate locations inside the framework folder. See documentation of the PRIVATE_HEADER , PUBLIC_HEADER , and RESOURCE target properties for details.

Either NAMELINK_ONLY or NAMELINK_SKIP may be specified as a LIBRARY option. 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_ONLY option causes installation of only the namelink when a library target is installed. The NAMELINK_SKIP option causes installation of library files other than the namelink when a library target is installed. When neither option is given both portions are installed. On platforms where versioned shared libraries do not have namelinks or when a library is not versioned the NAMELINK_SKIP option installs the library and the NAMELINK_ONLY option installs nothing. See the VERSION and SOVERSION target properties for details on creating versioned shared libraries.

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.

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.

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.

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.

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 . If a COMPONENT option is specified that does not match that given to the targets associated with the behavior is undefined. If a library target is included in the export but a target to which it links is not included the behavior is unspecified.

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

/lib/myproj/myproj.cmake . 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.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

  • Cmake find windows sdk
  • Cm6501 7 драйвер windows
  • Cm6206 driver windows 7
  • Cm108 driver windows 7
  • Cluster windows server 2008 r2 standard