как установить cmake на windows
Русские Блоги
Учебник по установке и использованию VSCode CMake
обзор
При использовании cmake для компиляции программ на C / C ++ в Windows вам сначала понадобится CMake, установите среду компиляции gcc / g ++, затем используйте VSCode и настройте CMakelist.txt.
Что такое CMake
Возможно, вы слышали о нескольких инструментах Make, таких как GNU Make, Qmake QT, MS nmake от Microsoft, BSD Make (pmake), Makepp и так далее. Эти инструменты Make следуют различным спецификациям и стандартам, и формат исполняемого ими файла Makefile сильно различается. Это создает серьезную проблему: если программное обеспечение хочет кросс-платформенное, оно должно гарантировать, что оно может быть скомпилировано на разных платформах. Если вы используете вышеупомянутый инструмент Make, вы должны написать Makefile для каждого стандарта, что будет сумасшедшей работой.
Обычно процесс генерации и компиляции Makefile с использованием CMake выглядит следующим образом:
готов
1. VSCode (следующие плагины должны быть установлены)
C/C++
C++ Intellisense
CMake
CMake tools
CMake Tools Helper
2. MinGW, руководство по установке [Портал】
3.CMake
Установить CMake
Настройте CMake в VSCode
Как правило, после того, как вы просто установите плагин CMake, вам будет автоматически предложено выбрать цепочку инструментов компиляции. Если подсказки нет или вы хотите заменить другие цепочки инструментов компиляции, вы можете использовать ctrl + shiftl + p, ввести следующие инструкции, а затем выбрать собственную установленную компиляцию во всплывающем окне. Цепочка для инструментов.
CMake:Select a Kit
Использование CMake
Теперь мы создаем каталог со следующей структурой:
Код main.c выглядит следующим образом:
Чтобы скомпилировать этот файл, мы редактируем файл CMakeLists.txt следующим образом:
Затем войдите в каталог Build и выполните cmake
Вывод выглядит следующим образом, и в папке Build создается много файлов, включая файл Makefile.
Файлы, содержащиеся в папке Build
На данный момент мы используем make Команда, вы можете скомпилировать нашу программу.
Наконец, попробуйте, результат нормальный.
Интеллектуальная рекомендация
AlamoFire Source Severtation Series (12) ось времени (временная шкала)
Эта статья приносит некоторые идеи о временной шкале в AlamoFire Преступность Перевод Timeline означает, что временная шкала может представлять событие с начала до конца узла времени. Концепция времен.
Анализ разницы между iOS initWithFrame, initWithCoder, awakeFromNib
Исследование соответствия типовых версий рамы
Знакомство с CMake. Часть 1. Установка, CMakeLists.txt, сборка.
Введение.
Многие, кто начинал создавать собственные программы, пользовался какой-либо системой сборки. В общем, система сборки – это набор инструментов, облегчающий работу с компилятором. Это включает в себя компиляцию, линковку, установку, а также сбор исходных файлов для передачи их компилятору и слежение за зависимостями. Также современные системы сборки облегчают работу с библиотеками, позволяют создавать переносимые проекты и выполняют ещё массу других вкусностей. Эта статья посвящена популярной системе сборки CMake и расскажет, как правильно её установить и настроить, а также будет рассмотрен простой пример её использования. Она рассчитана на тех, что хоть немного знаком с понятиями make, Makefile, компиляция, линковка.
Установка в Linux.
Для популярных дистрибутивов Linux типа Debian, Gentoo, Fedora и т.д. CMake давно лежит в официальных репозиториях. Нам нужно всего лишь установить пакет cmake с помощью менеджера пакетов. Как правило, он устанавливается в системные директории, и необходимости править переменные окружения нету. Можете проверить её работоспособность, выполнив
Если же в репозитории нет такого пакета, то можно его собрать вручную. Скачиваем Unix/Linux Source, например, cmake-3.5.0-rc3.tar.gz, распаковываем и собираем:
Установка в Windows.
Для Windows на сайте CMake лежит установочный файл msi. Рекомендую при установке отметить галочку добавления пути в переменные окружения PATH для всех пользователей. Тогда, после перелогинивания, CMake будет доступен из любого места. Проверить можно, открыв cmd и выполнив тот же
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. The Windows installer has an option to modify the system PATH environment variable. If that is not selected during installation, one may manually add the install directory (e.g. C:\Program Files\CMake\bin) to the PATH in a command prompt.
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.
macOS
There are pre-compiled binaries available on the Download page for macOS as disk images and tarballs. After copying CMake.app into /Applications (or a custom location), run it and follow the “How to Install For Command Line Use” menu item for instructions to make the command-line tools (e.g. cmake) available in the PATH. Or, one may manually add the install directory (e.g. /Applications/CMake.app/Contents/bin) to the PATH.
One may alternatively download and build CMake from source as in the following section.
Linux, 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.)
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:
Download Verification
Each release on the Download page comes with a file named cmake-$version-SHA-256.txt, where $version is the release version number.
One may use this file to verify other downloads, such as the source tarball. For example:
The SHA-256 file itself can be verified by GPG signature:
The GPG key C6C265324BBEBDC350B513D02D2CEF1034921684 is a signing subkey whose expiry is updated yearly.
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 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:
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:
On AIX, the linker import file created for executables with ENABLE_EXPORTS enabled.
Target artifacts of this kind include:
Shared libraries, except
on macOS when marked as FRAMEWORK (see below).
Target artifacts of this kind include:
DLLs (on all Windows-based systems including Cygwin; note that the accompanying import libraries are of kind ARCHIVE ).
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.
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.)
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.
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:
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.
The install(TARGETS) command can also accept the following options at the top level:
New in version 3.21.
This option causes all runtime dependencies of installed executable, shared library, and module targets to be added to the specified runtime dependency set. This set can then be installed with an install(RUNTIME_DEPENDENCY_SET) command.
This keyword and the RUNTIME_DEPENDENCIES keyword are mutually exclusive.
New in version 3.21.
RUNTIME_DEPENDENCIES is semantically equivalent to the following pair of calls:
where will be a randomly generated set name. The args. may include any of the following keywords supported by the install(RUNTIME_DEPENDENCY_SET) command:
The RUNTIME_DEPENDENCIES and RUNTIME_DEPENDENCY_SET keywords are mutually exclusive.
will install myExe to
The RUNTIME_DEPENDENCY_SET option causes the runtime artifacts of the imported executable, shared library, and module library targets to be added to the runtime dependency set. This set can then be installed with an install(RUNTIME_DEPENDENCY_SET) command.
Installing FilesВ¶
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.
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.
will extract and install header files from a source tree.
Some options may follow a PATTERN or REGEX expression as described under string(REGEX) 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
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.
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.21: When the ALL_COMPONENTS option is given, the custom installation script code will be executed for every component of a component-specific installation. This option is mutually exclusive with the COMPONENT option.
Installing ExportsВ¶
-config.cmake file or the latter may be incorrectly matched by the glob and loaded.
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
Installs a runtime dependency set previously created by one or more install(TARGETS) or install(IMPORTED_RUNTIME_ARTIFACTS) commands. The dependencies of targets belonging to a runtime dependency set are installed in the RUNTIME destination and component on DLL platforms, and in the LIBRARY destination and component on non-DLL platforms. macOS frameworks are installed in the FRAMEWORK destination and component. Targets built within the build tree will never be installed as runtime dependencies, nor will their own dependencies, unless the targets themselves are installed with install(TARGETS).
Полное руководство по CMake. Часть вторая: Система сборки
Введение
В данной статье рассмотрено использование системы сборки CMake, применяемой в колоссальном количестве проектов на C/C++. Строго рекомендуется прочитать первую часть руководства во избежание непонимания синтаксиса языка CMake, явным образом фигурирующего на протяжении всей статьи.
Запуск CMake
Ниже приведены примеры использования языка CMake, по которым Вам следует попрактиковаться. Экспериментируйте с исходным кодом, меняя существующие команды и добавляя новые. Чтобы запустить данные примеры, установите CMake с официального сайта.
Принцип работы
Система сборки CMake представляет из себя оболочку над другими платформенно зависимыми утилитами (например, Ninja или Make). Таким образом, в самом процессе сборки, как бы парадоксально это ни звучало, она непосредственного участия не принимает.
Система сборки CMake принимает на вход файл CMakeLists.txt с описанием правил сборки на формальном языке CMake, а затем генерирует промежуточные и нативные файлы сборки в том же каталоге, принятых на Вашей платформе.
Сгенерированные файлы будут содержать конкретные названия системных утилит, директорий и компиляторов, в то время как команды CMake орудуют лишь абстрактным понятием компилятора и не привязаны к платформенно зависимым инструментам, сильно различающихся на разных операционных системах.
Проверка версии CMake
Команда cmake_minimum_required проверяет запущенную версию CMake: если она меньше указанного минимума, то CMake завершает свою работу фатальной ошибкой. Пример, демонстрирующий типичное использование данной команды в начале любого CMake-файла:
Как подметили в комментариях, команда cmake_minimum_required выставляет все флаги совместимости (смотреть cmake_policy ). Некоторые разработчики намеренно выставляют низкую версию CMake, а затем корректируют функционал вручную. Это позволяет одновременно поддерживать древние версии CMake и местами использовать новые возможности.
Оформление проекта
В начале любого CMakeLists.txt следует задать характеристики проекта командой project для лучшего оформления интегрированными средами и прочими инструментами разработки.
Запуск скриптовых файлов
Команда include заменяет строку своего вызова кодом заданного файла, действуя аналогично препроцессорной команде include языков C/C++. Этот пример запускает скриптовый файл MyCMakeScript.cmake описанной командой:
Компиляция исполняемых файлов
Компиляция библиотек
Добавление исходников к цели
Повторяющиеся вызовы команды target_sources добавляют исходные файлы к цели в том порядке, в каком они были вызваны, поэтому нижние два блока кода являются функционально эквивалентными:
Генерируемые файлы
Важно подметить, что «DLL-платформами» считаются все платформы, основанные на Windows, в том числе и Cygwin.
Компоновка с библиотеками
Стоит отметить, что модульные библиотеки не подлежат компоновке с исполняемыми файлами или другими библиотеками, так как они предназначены исключительно для загрузки техниками выполнения.
Работа с целями
Как упомянули в комментариях, цели в CMake тоже подвержены ручному манипулированию, однако весьма ограниченному.
Имеется возможность управления свойствами целей, предназначенных для задания процесса сборки проекта. Команда get_target_property присваивает предоставленной переменной значение свойства цели. Данный пример выводит значение свойства C_STANDARD цели MyTarget на экран:
Пример выше задал цели MyTarget свойства, влияющие на процесс компиляции, а именно: при компиляции цели MyTarget CMake затребует компилятора о использовании стандарта C11. Все известные именования свойств целей перечисляются на этой странице.
Также имеется возможность проверки ранее определённых целей с помощью конструкции if(TARGET ) :
Добавление подпроектов
Команда add_subdirectory побуждает CMake к незамедлительной обработке указанного файла подпроекта. Пример ниже демонстрирует применение описанного механизма:
Стоит отметить, что все переменные из родительской области видимости унаследуются добавленным каталогом, а все переменные, определённые и переопределённые в данном каталоге, будут видимы лишь ему (если ключевое слово PARENT_SCOPE не было определено аргументом команды set ). Данную особенность упомянули в комментариях к предыдущей статье.
Поиск пакетов
Команда find_package находит и загружает настройки внешнего проекта. В большинстве случаев она применяется для последующей линковки внешних библиотек, таких как Boost и GSL. Данный пример вызывает описанную команду для поиска библиотеки GSL и последующей линковки:
В общем случае, команда find_package имеет две разновидности запуска: модульную и конфигурационную. Пример выше применял модульную форму. Это означает, что во время вызова команды CMake ищет скриптовый файл вида Find
Способы включения заголовков
Команда target_include_directories влияет лишь на указанную первым аргументом цель, а на другие цели никакого воздействия не оказывается. Пример ниже демонстрирует разницу между этими двумя командами:
Установка проекта
Команда install генерирует установочные правила для Вашего проекта. Данная команда способна работать с целями, файлами, папками и многим другим. Сперва рассмотрим установку целей.
После завершения обработки CMake всех Ваших файлов Вы можете выполнить установку всех описанных объектов командой sudo checkinstall (если CMake генерирует Makefile ), или же выполнить данное действие интегрированной средой разработки, поддерживающей CMake.
Наглядный пример проекта
Данное руководство было бы неполным без демонстрации реального примера использования системы сборки CMake. Рассмотрим схему простого проекта, использующего CMake в качестве единственной системы сборки:
Заключение
Теперь Вы способны писать свои и понимать чужие CMake-файлы, а подробно прочитать про остальные механизмы Вы можете на официальном сайте.
Следующая статья данного руководства будет посвящена тестированию и созданию пакетов с помощью CMake и выйдет через неделю. До скорых встреч!