Cmake command in windows

Содержание
  1. Cmake command in windows
  2. Структура CMakeLists.txt
  3. Автогенерация проекта для Visual Studio (Windows)
  4. Зависимости между библиотеками и приложениями
  5. Выбор стандарта и диалекта C++
  6. Функции в CMake
  7. Добавление исходников к цели с target_sources
  8. Интерфейс к утилитам командной строки
  9. Функция find_package
  10. Cmake command in windows
  11. Running CMake for Windows / Microsoft Visual C++ (MSVC)
  12. Running CMake on Unix
  13. Running CMake from the command line
  14. What is the CMake cache?
  15. Utility Targets produced
  16. cmake and make in Windows
  17. 2 Answers 2
  18. Проекты CMake в Visual Studio CMake projects in Visual Studio
  19. Установка Installation
  20. Интеграция с IDE IDE Integration
  21. Открытие существующего кэша Open an existing cache
  22. Создание проектов CMake Building CMake projects
  23. Отладка проектов CMake Debugging CMake projects
  24. «Только мой код» для проектов CMake Just My Code for CMake projects
  25. Интеграция с vcpkg Vcpkg integration
  26. Отзывы о настройке конфигурации Customize configuration feedback
  27. Изменение файлов CMakeLists.txt Editing CMakeLists.txt files
  28. Шаг настройки CMake CMake configure step
  29. Устранение ошибок кэша CMake Troubleshooting CMake cache errors
  30. Запуск CMake из командной строки Run CMake from the command line
  31. Установка Installation
  32. Интеграция с IDE IDE integration
  33. Импорт существующего кэша Import an existing cache
  34. Импорт существующего кэша To import an existing cache
  35. Создание проектов CMake Building CMake projects
  36. Отладка проектов CMake Debugging CMake projects
  37. Изменение файлов CMakeLists.txt Editing CMakeLists.txt files
  38. Шаг настройки CMake CMake configure step
  39. Устранение ошибок кэша CMake Troubleshooting CMake cache errors
  40. Компиляция одного файла Single file compilation
  41. Запуск CMake из командной строки Run CMake from the command line

Cmake command in windows

На первом шаге проект нужно сконфигурировать, то есть создать финальный скрипт сборки, запустив cmake в будущем каталоге сборки.

На втором шаге нужно запустить финальный скрипт. Не вызывайте make ! Утилита cmake сделает это сама:

Структура CMakeLists.txt

В начале главного файла CMakeLists.txt ставят метаинформацию о минимальной версии CMake и названии проекта:

Затем следует список инструкций, служащих для вычисления различных переменных, создания целей сборки, подключения проектов из подкаталогов и так далее. Например, подключить дополнительный CMakeLists.txt из подкаталога можно так:

Целью может стать исполняемый файл, собираемый из исходного кода

Целью также может быть библиотека, статическая или динамическая.

Автогенерация проекта для Visual Studio (Windows)

Если используется Visual C++, то путь немного другой: на шаге конфигурирования создаётся проект для Visual Studio, который затем можно собрать из IDE либо так же из командной строки.

Созданный проект Visual Studio нельзя изменять и использовать постоянно, потому что при генерации проекта используются абсолютные пути и другие неприемлемые для постоянной работы вещи.

Если проект был сконфигурирован успешно, то в каталоге ../myapp-build появятся автоматически сгенерированный BUILD_ALL.sln и проекты для Visual Studio. Их можно открыть к IDE, либо собрать из командной строки с помощью cmake. Названия опций говорят сами за себя:

Зависимости между библиотеками и приложениями

Не используйте директивы include_directories , add_definitions , add_compile_options ! Они меняют глобальные настройки для всех целей, это создаёт проблемы при масштабировании.

  • Используйте target_link_libraries для добавления статических и динамических библиотек, от которых зависит цель
  • Используйте target_include_directories вместо include_directories для добавления путей поиска заголовков, от которых зависит цель
  • Используйте target_compile_definitions вместо add_definitions для добавления макросов, с которыми собирается цель
  • Используйте target_compile_options для добавления специфичных флагов компилятора, с которыми собирается цель

Вы можете выбирать область видимости настройки:

  • PUBLIC делает настройку видимой для текущей цели и для всех зависящих от неё целей
  • PRIVATE делает настройку видимой только для текущей цели
  • INTERFACE делает настройку видимой только для всех зависящих от неё целей

Пример использования областей видимости:

Схема зависимостей условного проекта:

Выбор стандарта и диалекта C++

Для настройки стандарта и флагов языка C++ не добавляйте флаги напрямую!

В CMake версии 3.8+ вы можете прямо потребовать включить нужный стандарт:

В CMake версии до 3.7 включительно можно использовать set_target_properties (если не работает, то у вас слишком старый CMake):

Для разработчиков библиотек есть более тонкий контроль над возможностями языка:

Функции в CMake

CMake позволяет объявлять функции командами function(name) / endfunction() и макросы командами macro(name) / endmacro() . Предпочитайте функции, а не макросы, т.к. у функций есть своя область видимости переменных, а у макросов — нет.

Добавление исходников к цели с target_sources

Лучше добавлять специфичные исходники с помощью target_sources, а не с помощью дополнительных переменных.

Интерфейс к утилитам командной строки

Функция find_package

Функция find_package принимает имя библиотеки как аргумент и обращается к CMake, чтобы найти скрипт для настройки переменных данной библиотеки. В итоге при сборке либо возникает ошибка из-за того что пакет не найден, либо добавляются переменные, хранящие пути поиска заголовков, имена библиотек для компоновщика и другие параметры.

Пример подключения Boost, вызывающего встроенный в CMake скрипт FindBoost:

Пример подключения библиотеки Bullet с помощью встроенного скрипта FindBullet и компоновки с приложением my_app:

Cmake command in windows

Once CMake has been installed on your system using it to build a project is easy. We will cover the process for Windows and then UNIX.

Running CMake for Windows / Microsoft Visual C++ (MSVC)

Run cmake-gui.exe, which should be in your Start menu under Program Files, there may also be a shortcut on your desktop, or if you built from source, it will be in the build directory. A GUI will appear similar to what is shown below. The top two entries are the source code and binary directories. They allow you to specify where the source code is for what you want to compile and where the resulting binaries should be placed. You should set these two values first. If the binary directory you specify does not exist, it will be created for you.

Running CMake on Unix

On most unix platforms, if the curses library is supported, cmake will build an executable called ccmake. This interface is a terminal based text application that is very similar to the windows GUI. To run ccmake, change directories into the directory where you want the binaries to be placed. This can be the same directory as the source code for what we call in-place builds (the binaries are in the same place as the source code) or it can be a new directory you create. Then run ccmake with either no arguments for an in-place-build, or with the path to the source directory on the command line. This will start the text interface that looks something like this:

If you hit the “c” key, it will configure the project. You should use that as you change values in the cache. To change values, use the arrow keys to select cache entries, and the enter key to edit them. Boolean values will toggle with the enter key. Once you have set all the values as you like, you can hit the ‘G” key to generate the makefiles and exit. You can also hit “h” for help, “q” to quit, and “t” to toggle the viewing of advanced cache entries.

Two examples of CMake usage on the Unix platform follow for a hello world project called Hello. In the first example, and in-place build is performed, i.e., the binaries are placed in the same directory as the source code.

In the second example, an out-of-place build is performed, i.e., the source code, libraries, and executables are produced in a directory separate from the source code directory(ies).

Running CMake from the command line

From the command line, cmake can be run as an interactive question and answer session or as a non-interactive program. To run in interactive mode, just pass the option “-i” to cmake. This will cause cmake to ask you to enter a value for each value in the cache file for the project. The process stops when there are no longer any more questions to ask.

Using CMake to build a project in non-interactive mode is a simple process if the project does not have many options. For larger projects like VTK, using ccmake, cmake -i, or CMakeSetup is recommended. This is because as you change options in the CMakeCache.txt file, cmake may add new entries to that file. It can be difficult to know when to stop the run cmake, edit the cache file cycle without the aid of an interface.

To build with just cmake change directory into where you want the binaries to be placed. For an in-place build you then run cmake and it will produce a CMakeCache.txt file that contains build options that you can adjust using any text editor. For non in-place builds the process is the same except you run cmake and provide the path to the source code as its argument. Once you have edited the CMakeCache.txt file you rerun cmake, repeat this process until you are happy with the cache settings. The type make and your project should compile. Some projects will have install targets as well so you can type make install to install them.

When running cmake from the command line, it is possible to specify command line options to cmake that will set values in the cache. This is done with a -DVARIABLE:TYPE=VALUE syntax on the command line. This is useful for non-interactive nightly test builds.

What is the CMake cache?

The cache is best thought of as a configuration file. Indeed Unix users could consider the cache as equivalent to the set of flags passed to the configure command. The first time CMake is run, it produces a CMakeCache.txt file. This file contains things like the existence and location of native JPEG library. The entries are added in response to certain CMake commands (e.g. FIND_LIBRARY) as they are processed anywhere in CMakeLists files anywhere in the source tree. After CMake has been run, and created a CMakeCache.txt file – you may edit it. The CMake GUI, will allow you to edit the options easily, or you can edit the file directly. The main reason for editing the cache would be to give CMake the location of a native library such as JPEG, or to stop it from using a native library and use a version of the library in your source tree.

CMake will not alter an existing entry in the cache file itself. If your CMakeLists.txt files change significantly, you will need to remove the relevant entries from the cache file. If you have not already hand-edited the cache file, you could just delete it before re-running CMake.

Why do I have to edit the cache more than once for some projects?
Some projects are very complex and setting one value in the cache may cause new options to appear the next time the cache is built. For example, VTK supports the use of MPI for performing distributed computing. This requires the build process to determine where the MPI libraries and header files are and to let the user adjust their values. But MPI is only available if another option VTK_USE_PARALLEL is first turned on in VTK. So to avoid confusion for people who don’t know what MPI is, we hide those options until VTK_USE_PARALLEL is turned on. So CMake shows the VTK_USE_PARALLEL option in the cache area, if the user turns that on and rebuilds the cache, new options will appear for MPI that they can then set. The rule is to keep building the cache until it doesn’t change. For most projects this will be just once. For some complicated ones it will be twice.

Utility Targets produced

In addition to the targets and rules to build object files, libraries and executables of a project, CMake creates some additional targets and rules. For Visual Studio projects, two utility projects are automatically created: ALL_BUILD and RUN_TESTS.

cmake and make in Windows

I understand that in linux cmake, make and make install can be combined together to produce a release. For example:

In windows, however, I cannot find similar commands that can do the same job. Usually, what is done is to build a .sln project first if Visual Studio is used, after that compile the .sln project and in the end run the INSTALL project. Will it be possible to make a release with several commands as it has been done in Linux. Many thanks.

Читайте также:  Oculus rift dk2 настройка windows 10

2 Answers 2

You can use msbuild instead of make:

or you could use CMake’s —build argument:

If you need the equivalent of the make command with no args (i.e. make all ) you would build the ALL_BUILD target as well, but this is built as part of the INSTALL target anyway.

In addition to Fraser’s answer, to get the first solution to work, one might need to call MSBuild in CMD as Administrator from the original path

Replace YEAR and EDITION with your corresponding values e.g. 2017 and Community

You might receive the following error, which means your enviroment variable is not set.

error MSB4019: The imported project «C:\Microsoft.Cpp.Default.props» was not found. Confirm that the path in the declaration is correct, and that the file exists on disk.

The enviroment variable can be set directly in the system settings or with CMD as Administrator. (Source for reference)

for Visual Studio 2015 and below:

Replace vXXX with your corresponding version e.g. 140

for Visual Studio 2017 and above:

Replace YEAR and EDITION with your corresponding values e.g. 2017 and Community

Edit:

I’ve also noticed that some solutions in Visual Studio 2017 wont show their contents in the Solution Explorer if the enviroment variable is set. Just remove them again if necessary.

Проекты CMake в Visual Studio CMake projects in Visual Studio

CMake — это кроссплатформенное средство с открытым кодом, которое позволяет определять процессы сборки, выполняемые на множестве платформ. CMake is a cross-platform, open-source tool for defining build processes that run on multiple platforms. В этой статье предполагается, что вы уже знакомы с CMake. This article assumes you’re familiar with CMake. См. документацию по CMake для получения дополнительных сведений. For more information about CMake, see the CMake documentation. Рекомендуем воспользоваться учебником по CMake в качестве отправной точки. The CMake tutorial is a good starting point to learn more.

За последние несколько выпусков была улучшена интеграция CMake с Visual Studio. CMake has become more and more integrated with Visual Studio over the past few releases. Чтобы ознакомиться с документацией по предпочтительной версии Visual Studio, используйте селектор Версия. To see the documentation for your preferred version of Visual Studio, use the Version selector control. Он находится в верхней части оглавления на этой странице. It’s found at the top of the table of contents on this page.

Компонент Средства CMake C++ для Windows использует функцию Открыть папку, чтобы напрямую использовать файлы проекта CMake (например, CMakeLists.txt) для IntelliSense и просмотра. The C++ CMake tools for Windows component uses the Open Folder feature to consume CMake project files (such as CMakeLists.txt) directly for the purposes of IntelliSense and browsing. Поддерживаются генераторы Visual Studio и Ninja. Both Ninja and Visual Studio generators are supported. Если вы используете генератор Visual Studio, он создает временный файл проекта и передает его в msbuild.exe. If you use a Visual Studio generator, it generates a temporary project file and passes it to msbuild.exe. Однако проект никогда не загружается для IntelliSense или просмотра. However, the project is never loaded for IntelliSense or browsing purposes. Также можно импортировать существующий кэш CMake. You can also import an existing CMake cache.

Установка Installation

Средства C++ CMake для Windows устанавливаются в рамках рабочих нагрузок Разработка классических приложений на C++ и Разработка приложений для Linux на C++ . C++ CMake tools for Windows is installed as part of the Desktop development with C++ and Linux Development with C++ workloads. Дополнительные сведения см. в статье Кроссплатформенные проекты CMake. For more information, see Cross-platform CMake projects.

Интеграция с IDE IDE Integration

Если выбрать Файл > Открыть > Папка, чтобы открыть папку, содержащую файл CMakeLists.txt, происходит следующее: When you choose File > Open > Folder to open a folder containing a CMakeLists.txt file, the following things happen:

Visual Studio добавляет пункт CMake в меню Проект с командами для просмотра и редактирования сценариев CMake. Visual Studio adds CMake items to the Project menu, with commands for viewing and editing CMake scripts.

Обозреватель решений отображает структуру папок и файлы. Solution Explorer displays the folder structure and files.

Visual Studio запускает cmake.exe и создает файл кэша CMake (CMakeCache.txt) для конфигурации по умолчанию (x64-Debug). Visual Studio runs cmake.exe and generates the CMake cache file (CMakeCache.txt) for the default (x64 Debug) configuration. В окне вывода отображается командная строка CMake, а также дополнительные выходные данные CMake. The CMake command line is displayed in the Output Window, along with additional output from CMake.

В фоновом режиме Visual Studio индексирует исходные файлы для поддержки функций IntelliSense, просмотра информации, рефакторинга и т. д. In the background, Visual Studio starts to index the source files to enable IntelliSense, browsing information, refactoring, and so on. По мере работы Visual Studio отслеживает изменения в редакторе, а также на диске, чтобы синхронизировать индекс с источниками. As you work, Visual Studio monitors changes in the editor and also on disk to keep its index in sync with the sources.

Вы можете открыть папки, содержащие любое количество проектов CMake. You can open folders containing any number of CMake projects. Visual Studio обнаруживает и настраивает все «корневые» файлы CMakeLists.txt в рабочей области. Visual Studio detects and configures all the «root» CMakeLists.txt files in your workspace. Операции CMake (настройка, сборка, отладка), C++ IntelliSense и просмотр доступны для всех проектов CMake в вашей рабочей области. CMake operations (configure, build, debug), C++ IntelliSense, and browsing are available to all CMake projects in your workspace.

Вы также можете просмотреть проекты, логически упорядоченные по целевым объектам. You can also view your projects organized logically by targets. Выберите Представление целевых объектов из раскрывающегося списка на панели инструментов в обозревателе решений: Choose Targets view from the dropdown in the Solution Explorer toolbar:

Нажмите кнопку Показать все файлы в верхней части Обозревателя решений, чтобы просмотреть все выходные данные, созданные CMake, в папках out/build/ . Click the Show All Files button at the top of Solution Explorer to see all the CMake-generated output in the out/build/ folders.

Visual Studio использует файл конфигурации с именем CMakeSettings.json. Visual Studio uses a configuration file called CMakeSettings.json. Этот файл также позволяет определять и хранить несколько конфигураций сборки и с удобством переключаться между ними в IDE. This file lets you define and store multiple build configurations, and conveniently switch between them in the IDE. Конфигурация — это конструкция Visual Studio, которая инкапсулирует параметры, относящиеся к конкретному типу сборки. A configuration is a Visual Studio construct that encapsulates settings that are specific to a given build type. Параметры используются для настройки параметров командной строки по умолчанию, которые Visual Studio передает в cmake.exe. The settings are used to configure the default command-line options that Visual Studio passes to cmake.exe. Здесь также можно указать дополнительные параметры CMake и определить любые дополнительные переменные. You can also specify additional CMake options here, and define any additional variables you like. Все параметры записываются в кэш CMake как внутренние или внешние переменные. All options are written to the CMake cache either as internal or external variables. В Visual Studio 2019 редактор параметров CMake предоставляет удобный способ изменения параметров. In Visual Studio 2019, the CMake Settings Editor provides a convenient way to edit your settings. Дополнительные сведения см. в статье Настраиваемые параметры CMake. For more information, see Customize CMake settings.

Один параметр, intelliSenseMode , не передается в CMake и используется только в Visual Studio. One setting, intelliSenseMode isn’t passed to CMake, but is used only by Visual Studio.

Используйте файл CMakeLists.txt в каждой папке проекта так же, как в любом проекте CMake. Use the CMakeLists.txt file in each project folder just as you would in any CMake project. Вы можете указывать исходные файлы, находить библиотеки, устанавливать параметры компилятора и компоновщика и указывать другие сведения о системе сборки. You can specify source files, find libraries, set compiler and linker options, and specify other build system-related information.

Чтобы передавать аргументы для исполняемого файла во время отладки, можно использовать другой файл с именем launch.vs.json. To pass arguments to an executable at debug time, you can use another file called launch.vs.json. В некоторых сценариях Visual Studio автоматически создает эти файлы. In some scenarios, Visual Studio automatically generates these files. Вы можете изменить их вручную или даже создать файл самостоятельно. You can edit them manually, or even create the file yourself.

Для других типов проектов «Открыть папку» используются два дополнительных файла JSON: CppProperties.json и tasks.vs.json. For other kinds of Open Folder projects, two additional JSON files are used: CppProperties.json and tasks.vs.json. Ни один из них не связан с проектами CMake. Neither of these are relevant for CMake projects.

Открытие существующего кэша Open an existing cache

При открытии существующего файла кэша CMake (CMakeCache. txt) Visual Studio не пытается управлять кэшем и деревом сборки. When you open an existing CMake cache file (CMakeCache.txt), Visual Studio doesn’t try to manage your cache and build tree for you. Настраиваемые или предпочтительные инструменты имеют полный контроль над тем, как CMake настраивает проект. Your custom or preferred tools have complete control over how CMake configures your project. Чтобы открыть существующий кэш в Visual Studio, выберите Файл > Открыть > CMake. To open an existing cache in Visual Studio, choose File > Open > CMake. Затем перейдите к существующему файлу CMakeCache.txt. Then, navigate to an existing CMakeCache.txt file.

Существующий кэш CMake можно добавить в открытый проект. You can add an existing CMake cache to an open project. Этот процесс аналогичен добавлению новой конфигурации. It’s done the same way you’d add a new configuration. Дополнительные сведения см. в записи блога об открытии существующего кэша в Visual Studio. For more information, see our blog post on opening an existing cache in Visual Studio.

Создание проектов CMake Building CMake projects

Для создания проекта CMake доступны следующие варианты: To build a CMake project, you have these choices:

На панели инструментов «Общие» найдите раскрывающийся список Конфигурация. In the General toolbar, find the Configurations dropdown. По умолчанию, возможно, отображается «x64-Debug». It probably shows «x64-Debug» by default. Выберите предпочтительную конфигурацию и нажмите клавишу F5 или кнопку Выполнить (с зеленым треугольником) на панели инструментов. Select the preferred configuration and press F5, or click the Run (green triangle) button on the toolbar. Сначала автоматически выполняется сборка проекта как решения Visual Studio. The project automatically builds first, just like a Visual Studio solution.

Щелкните CMakeLists.txt правой кнопкой мыши и выберите пункт Сборка. Right click on CMakeLists.txt and select Build from the context menu. Если в структуре папок имеется несколько целевых объектов, можно выбрать сборку их всех или только одного из них. If you have multiple targets in your folder structure, you can choose to build all or only one specific target.

В главном меню выберите Сборка > Собрать все (нажмите клавишу F7 или клавиши CTRL+SHIFT+B). From the main menu, select Build > Build All (F7 or Ctrl+Shift+B). Убедитесь, что целевой объект CMake уже выбран в раскрывающемся списке Автозапускаемый элемент на панели инструментов Общие. Make sure that a CMake target is already selected in the Startup Item dropdown in the General toolbar.

Как и следовало ожидать, результаты сборки отображаются в окне вывода и списке ошибок. As you would expect, build results are shown in the Output Window and Error List.

В папке с несколькими целевыми объектами сборки можно указать целевой объект CMake для сборки: Выберите элемент Сборка в меню CMake или контекстном меню CMakeLists.txt, чтобы указать целевой объект. In a folder with multiple build targets, you can specify which CMake target to build: Choose the Build item on the CMake menu or the CMakeLists.txt context menu to specify the target. Нажмите клавиши CTRL+SHIFT+B в проекте CMake, чтобы выполнить сборку текущего активного документа. If you enter Ctrl+Shift+B in a CMake project, it builds the current active document.

Читайте также:  Dvd студия windows аналог

Отладка проектов CMake Debugging CMake projects

Для отладки проекта CMake выберите требуемую конфигурацию и нажмите клавишу F5 или кнопку Выполнить на панели инструментов. To debug a CMake project, choose the preferred configuration and press F5, or press the Run button in the toolbar. Если для кнопки Выполнить отображается сообщение «Выбрать элемент запуска», выберите стрелку раскрывающегося списка. If the Run button says «Select Startup Item», select the dropdown arrow. Выберите нужный целевой объект. Choose the target that you want to run. (В проекте CMake параметр «Текущий документ» допустим только для файлов CPP.) (In a CMake project, the «Current document» option is only valid for .cpp files.)

Команды Выполнить или F5 сначала выполняют сборку проекта, если с момента предыдущей сборки были внесены изменения. The Run or F5 commands first build the project if changes have been made since the previous build. Изменения в CMakeSettings.json вызывают повторное создание кэша CMake. Changes to CMakeSettings.json cause the CMake cache to be regenerated.

Вы можете настроить сеанс отладки CMake, задав свойства в файле launch.vs.json. You can customize a CMake debugging session by setting properties in the launch.vs.json file. Дополнительные сведения см. в разделе Настройка сеансов отладки CMake. For more information, see Configure CMake debugging sessions.

«Только мой код» для проектов CMake Just My Code for CMake projects

При сборке для Windows с помощью компилятора MSVC в проектах CMake поддерживается отладка «Только мой код». When you build for Windows using the MSVC compiler, CMake projects have support for Just My Code debugging. Чтобы изменить параметр «Только мой код», перейдите в раздел Сервис > Параметры > Отладка > Общие. To change the Just My Code setting, go to Tools > Options > Debugging > General.

Интеграция с vcpkg Vcpkg integration

Если вы установили vcpkg, то проекты CMake, открытые в Visual Studio, автоматически интегрируют файл цепочки инструментов vcpkg. If you have installed vcpkg, CMake projects opened in Visual Studio automatically integrate the vcpkg toolchain file. Это означает, что для использования vcpkg с проектами CMake не требуется дополнительная настройка. That means no additional configuration is required to use vcpkg with your CMake projects. Эта поддержка работает как для локальных установок vcpkg, так и для vcpkg в удаленных системах, которые вы намерены использовать. This support works for both local vcpkg installations and vcpkg installations on remote systems that you’re targeting. Это поведение автоматически отключается при указании любых других цепочек инструментов в конфигурации параметров CMake. This behavior is disabled automatically when you specify any other toolchain in your CMake Settings configuration.

Отзывы о настройке конфигурации Customize configuration feedback

По умолчанию большинство сообщений конфигурации подавляются, если нет ошибки. By default, most configuration messages are suppressed unless there’s an error. Чтобы просмотреть все сообщения, включите эту функцию в разделе Средства > Параметры > CMake. You can see all messages by enabling this feature in Tools > Options > CMake.

Изменение файлов CMakeLists.txt Editing CMakeLists.txt files

Чтобы изменить файл CMakeLists.txt, щелкните его правой кнопкой мыши в обозревателе решений и выберите пункт Открыть. To edit a CMakeLists.txt file, right-click on the file in Solution Explorer and choose Open. Если вы вносите изменения в файл, отображается желтая строка состояния, которая сообщает о предстоящем обновлении IntelliSense. If you make changes to the file, a yellow status bar appears and informs you that IntelliSense will update. Это дает возможность отменить операцию обновления. It gives you a chance to cancel the update operation. Сведения о CMakeLists.txt см. в документации по CMake. For information about CMakeLists.txt, see the CMake documentation.

Сразу после сохранения файла автоматически перезапускается этап настройки, отображающий информацию в окне вывода. As soon as you save the file, the configuration step automatically runs again and displays information in the Output window. Ошибки и предупреждения отображаются в списке ошибок или окне вывода. Errors and warnings are shown in the Error List or Output window. Дважды щелкните ошибку в окне Список ошибок, чтобы перейти к строке с ошибкой в CMakeLists.txt. Double-click on an error in the Error List to navigate to the offending line in CMakeLists.txt.

Шаг настройки CMake CMake configure step

При внесении существенных изменений в файл CMakeSettings.json или CMakeLists.txt Visual Studio автоматически перезапускает шаг настройки CMake. When you make significant changes to the CMakeSettings.json or to CMakeLists.txt files, Visual Studio automatically reruns the CMake configure step. Если шаг настройки завершается без ошибок, собранные данные становятся доступны в C++ IntelliSense и языковых службах. If the configure step finishes without errors, the information that’s collected is available in C++ IntelliSense and language services. Они также используются в операциях сборки и отладки. It’s also used in build and debug operations.

Устранение ошибок кэша CMake Troubleshooting CMake cache errors

Если вам нужны дополнительные сведения о состоянии кэша CMake для диагностики проблемы, откройте главное меню Проект или контекстное меню CMakeLists.txt в обозревателе решений, чтобы выполнить одну из следующих команд: If you need more information about the state of the CMake cache to diagnose a problem, open the Project main menu or the CMakeLists.txt context menu in Solution Explorer to run one of these commands:

Просмотреть кэш открывает файл CMakeCache.txt из корневой папки сборки в редакторе. View Cache opens the CMakeCache.txt file from the build root folder in the editor. (Любые внесенные здесь изменения в CMakeCache.txt удаляются при очистке кэша. (Any edits you make here to CMakeCache.txt are wiped out if you clean the cache. Сведения о внесении изменений, сохраняемых после очистки кэша, см. в разделе Настройка параметров CMake.) To make changes that persist after the cache is cleaned, see Customize CMake settings.)

Открыть папку кэша открывает окно проводника с корневой папкой сборки. Open Cache Folder opens an Explorer window to the build root folder.

Очистить кэш удаляет корневую папку сборки, чтобы следующий шаг настройки CMake начинался с очистки кэша. Clean Cache deletes the build root folder so that the next CMake configure step starts from a clean cache.

Создать кэш принудительно создает шаг для выполнения, даже если Visual Studio считает среду актуальной. Generate Cache forces the generate step to run even if Visual Studio considers the environment up to date.

Вы можете отключить автоматическое создание кэша в диалоговом окне Сервис > Параметры > CMake > Общие. Automatic cache generation can be disabled in the Tools > Options > CMake > General dialog.

Запуск CMake из командной строки Run CMake from the command line

Если вы установили CMake из Visual Studio Installer, можете запустить это средство из командной строки, сделав следующее: If you have installed CMake from the Visual Studio Installer, you can run it from the command line by following these steps:

Запустите соответствующий файл vsdevcmd.bat (x86 или x64). Run the appropriate vsdevcmd.bat (x86/x64). Дополнительные сведения см. в статье Сборка из командной строки. For more information, see Building on the Command Line.

Перейдите в папку выходных данных. Switch to your output folder.

Запустите CMake для создания или настройки приложения. Run CMake to build/configure your app.

В Visual Studio 2017 существует широкая поддержка CMake, включая кроссплатформенные проекты CMake. Visual Studio 2017 has rich support for CMake, including cross-platform CMake projects. Компонент Инструменты Visual C++ для CMake использует функцию Открыть папку, чтобы позволить интегрированной среде разработки использовать файлы проекта CMake (например, CMakeLists.txt) для IntelliSense и просмотра. The Visual C++ Tools for CMake component uses the Open Folder feature to enable the IDE to consume CMake project files (such as CMakeLists.txt) directly for the purposes of IntelliSense and browsing. Поддерживаются генераторы Visual Studio и Ninja. Both Ninja and Visual Studio generators are supported. Если вы используете генератор Visual Studio, он создает временный файл проекта и передает его в msbuild.exe. If you use a Visual Studio generator, it generates a temporary project file and passes it to msbuild.exe. Однако проект никогда не загружается для IntelliSense или просмотра. However, the project is never loaded for IntelliSense or browsing purposes. Также можно импортировать существующий кэш CMake. You also can import an existing CMake cache.

Установка Installation

Средства Visual C++ для CMake устанавливаются в рамках рабочих нагрузок Разработка классических приложений на C++ и Разработка приложений для Linux на C++ . Visual C++ Tools for CMake is installed as part of the Desktop development with C++ and Linux Development with C++ workloads.

Интеграция с IDE IDE integration

Если выбрать Файл > Открыть > Папка, чтобы открыть папку, содержащую файл CMakeLists.txt, происходит следующее: When you choose File > Open > Folder to open a folder containing a CMakeLists.txt file, the following things happen:

Visual Studio добавляет пункт CMake в главное меню с командами для просмотра и редактирования сценариев CMake. Visual Studio adds a CMake menu item to the main menu, with commands for viewing and editing CMake scripts.

Обозреватель решений отображает структуру папок и файлы. Solution Explorer displays the folder structure and files.

Visual Studio запускает CMake.exe и при необходимости создает кэш CMake для конфигурации по умолчанию, которой является отладка x86. Visual Studio runs CMake.exe and optionally generates the CMake cache for the default configuration, which is x86 Debug. В окне вывода отображается командная строка CMake, а также дополнительные выходные данные CMake. The CMake command line is displayed in the Output Window, along with additional output from CMake.

В фоновом режиме Visual Studio индексирует исходные файлы для поддержки функций IntelliSense, просмотра информации, рефакторинга и т. д. In the background, Visual Studio starts to index the source files to enable IntelliSense, browsing information, refactoring, and so on. По мере работы Visual Studio отслеживает изменения в редакторе, а также на диске, чтобы синхронизировать индекс с источниками. As you work, Visual Studio monitors changes in the editor and also on disk to keep its index in sync with the sources.

Вы можете открыть папки, содержащие любое количество проектов CMake. You can open folders containing any number of CMake projects. Visual Studio обнаруживает и настраивает все «корневые» файлы CMakeLists.txt в рабочей области. Visual Studio detects and configures all the «root» CMakeLists.txt files in your workspace. Операции CMake (настройка, сборка, отладка), C++ IntelliSense и просмотр доступны для всех проектов CMake в вашей рабочей области. CMake operations (configure, build, debug), C++ IntelliSense, and browsing are available to all CMake projects in your workspace.

Вы также можете просмотреть проекты, логически упорядоченные по целевым объектам. You can also view your projects organized logically by targets. Выберите Представление целевых объектов из раскрывающегося списка на панели инструментов в обозревателе решений: Choose Targets view from the dropdown in the Solution Explorer toolbar:

Visual Studio использует файл с именем CMakeSettings.json для хранения переменных среды или параметров командной строки для Cmake.exe. Visual Studio uses a file called CMakeSettings.json to store environment variables or command-line options for Cmake.exe. CMakeSettings.json также позволяет определить и сохранить несколько конфигураций сборки CMake. CMakeSettings.json also enables you to define and store multiple CMake build configurations. Вы можете легко переключаться между ними в интегрированной среде разработки. You can conveniently switch between them in the IDE.

Или используйте CMakeLists.txt так же, как в любом проекте CMake, чтобы указывать исходные файлы, находить библиотеки, устанавливать параметры компилятора и компоновщика и указывать другие сведения о системе сборки. Otherwise, use the CMakeLists.txt just as you would in any CMake project to specify source files, find libraries, set compiler and linker options, and specify other build system-related information.

Чтобы передавать аргументы для исполняемого файла во время отладки, можно использовать другой файл с именем launch.vs.json. If you need to pass arguments to an executable at debug time, you can use another file called launch.vs.json. В некоторых сценариях Visual Studio автоматически создает эти файлы. In some scenarios, Visual Studio automatically generates these files. Вы можете изменить их вручную или даже создать файл самостоятельно. You can edit them manually, or even create the file yourself.

Для других типов проектов «Открыть папку» используются два дополнительных файла JSON: CppProperties.json и tasks.vs.json. For other kinds of Open Folder projects, two additional JSON files are used: CppProperties.json and tasks.vs.json. Ни один из них не связан с проектами CMake. Neither of these are relevant for CMake projects.

Читайте также:  Have both linux and windows

Импорт существующего кэша Import an existing cache

Когда вы импортируете существующий файл CMakeCache.txt, Visual Studio автоматически извлекает настраиваемые переменные и создает на их основе предварительно заполненный файл CMakeSettings.json. When you import an existing CMakeCache.txt file, Visual Studio automatically extracts customized variables and creates a pre-populated CMakeSettings.json file based on them. Исходный кэш никак не изменяется. The original cache isn’t modified in any way. Его по-прежнему можно использовать из командной строки или с помощью любого средства или интегрированной среды разработки, которые использовались для его создания. It can still be used from the command line, or with whatever tool or IDE used to generate it. Новый файл CMakeSettings.json помещается рядом с корневым файлом CMakeLists.txt проекта. The new CMakeSettings.json file is placed alongside the project’s root CMakeLists.txt. Visual Studio создает кэш на основе файла параметров. Visual Studio generates a new cache based the settings file. Вы можете переопределить автоматическое создание кэша в диалоговом окне Сервис > Параметры > CMake > Общие. You can override automatic cache generation in the Tools > Options > CMake > General dialog.

Импортируется не все содержимое кэша. Not everything in the cache is imported. Такие свойства, как генератор и расположение компиляторов, заменяются значениями по умолчанию, хорошо совместимыми с данной интегрированной средой разработки. Properties such as the generator and the location of the compilers are replaced with defaults that are known to work well with the IDE.

Импорт существующего кэша To import an existing cache

В главном меню выберите Файл > Открыть > CMake: From the main menu, choose File > Open > CMake:

Эта команда открывает мастер импорта CMake из кэша. This command brings up the Import CMake from Cache wizard.

Перейдите к файлу CMakeCache.txt, который хотите импортировать, и нажмите кнопку ОК. Navigate to the CMakeCache.txt file that you want to import, and then click OK. Отображается мастер импорта CMake из кэша: The Import CMake Project from Cache wizard appears:

По завершении работы мастера вы увидите новый файл CMakeCache.txt в обозревателе решений рядом с корневым файлом CMakeLists.txt в проекте. When the wizard completes, you can see the new CMakeCache.txt file in Solution Explorer next to the root CMakeLists.txt file in your project.

Создание проектов CMake Building CMake projects

Для создания проекта CMake доступны следующие варианты: To build a CMake project, you have these choices:

На панели инструментов «Общие» найдите раскрывающийся список Конфигурация. In the General toolbar, find the Configurations dropdown. По умолчанию, скорее всего, отображается «Linux-Debug» или «x64-Debug». It’s probably showing «Linux-Debug» or «x64-Debug» by default. Выберите предпочтительную конфигурацию и нажмите клавишу F5 или кнопку Выполнить (с зеленым треугольником) на панели инструментов. Select the preferred configuration and press F5, or click the Run (green triangle) button on the toolbar. Сначала автоматически выполняется сборка проекта как решения Visual Studio. The project automatically builds first, just like a Visual Studio solution.

Щелкните CMakeLists.txt правой кнопкой мыши и выберите пункт Сборка. Right click on the CMakeLists.txt and select Build from the context menu. Если в структуре папок имеется несколько целевых объектов, можно выбрать сборку их всех или только одного из них. If you have multiple targets in your folder structure, you can choose to build all or only one specific target.

В главном меню выберите Сборка > Собрать решение (нажмите клавишу F7 или клавиши CTRL+SHIFT+B). From the main menu, select Build > Build Solution (F7 or Ctrl+Shift+B). Убедитесь, что целевой объект CMake уже выбран в раскрывающемся списке Автозапускаемый элемент на панели инструментов Общие. Make sure that a CMake target is already selected in the Startup Item dropdown in the General toolbar.

Вы можете настраивать конфигурации сборки, переменные среды, аргументы командной строки и другие параметры в файле CMakeSettings.json. You can customize build configurations, environment variables, command-line arguments, and other settings in the CMakeSettings.json file. Это позволяет вносить изменения, не изменяя файл CMakeLists.txt. It lets you make changes without modifying the CMakeLists.txt file. Дополнительные сведения см. в статье Настраиваемые параметры CMake. For more information, see Customize CMake settings.

Как и следовало ожидать, результаты сборки отображаются в окне вывода и списке ошибок. As you would expect, build results are shown in the Output Window and Error List.

В папке с несколькими целевыми объектами сборки можно указать целевой объект CMake для сборки: Выберите элемент Сборка в меню CMake или контекстном меню CMakeLists.txt, чтобы указать целевой объект. In a folder with multiple build targets, you can specify which CMake target to build: Choose the Build item on the CMake menu or the CMakeLists.txt context menu to specify the target. Нажмите клавиши CTRL+SHIFT+B в проекте CMake, чтобы выполнить сборку текущего активного документа. If you enter Ctrl+Shift+B in a CMake project, it builds the current active document.

Отладка проектов CMake Debugging CMake projects

Для отладки проекта CMake выберите требуемую конфигурацию и нажмите клавишу F5. To debug a CMake project, choose the preferred configuration and press F5. Или нажмите кнопку Выполнить на панели инструментов. Or, press the Run button in the toolbar. Если для кнопки Выполнить отображается сообщение «Выбрать элемент запуска», выберите стрелку раскрывающегося списка и выберите целевой объект, который требуется запустить. If the Run button says «Select Startup Item», select the dropdown arrow and choose the target that you want to run. (В проекте CMake параметр «Текущий документ» допустим только для файлов CPP.) (In a CMake project, the «Current document» option is only valid for .cpp files.)

Команды Выполнить или F5 сначала выполняют сборку проекта, если с момента предыдущей сборки были внесены изменения. The Run or F5 commands first build the project if changes have been made since the previous build.

Вы можете настроить сеанс отладки CMake, задав свойства в файле launch.vs.json. You can customize a CMake debugging session by setting properties in the launch.vs.json file. Дополнительные сведения см. в разделе Настройка сеансов отладки CMake. For more information, see Configure CMake debugging sessions.

Изменение файлов CMakeLists.txt Editing CMakeLists.txt files

Чтобы изменить файл CMakeLists.txt, щелкните его правой кнопкой мыши в обозревателе решений и выберите пункт Открыть. To edit a CMakeLists.txt file, right-click on the file in Solution Explorer and choose Open. Если вы вносите изменения в файл, отображается желтая строка состояния, которая сообщает о предстоящем обновлении IntelliSense. If you make changes to the file, a yellow status bar appears and informs you that IntelliSense will update. Это дает возможность отменить операцию обновления. It gives you a chance to cancel the update operation. Сведения о CMakeLists.txt см. в документации по CMake. For information about CMakeLists.txt, see the CMake documentation.

Сразу после сохранения файла автоматически перезапускается этап настройки, отображающий информацию в окне вывода. As soon as you save the file, the configuration step automatically runs again and displays information in the Output window. Ошибки и предупреждения отображаются в списке ошибок или окне вывода. Errors and warnings are shown in the Error List or Output window. Дважды щелкните ошибку в окне Список ошибок, чтобы перейти к строке с ошибкой в CMakeLists.txt. Double-click on an error in the Error List to navigate to the offending line in CMakeLists.txt.

Шаг настройки CMake CMake configure step

При внесении существенных изменений в файл CMakeSettings.json или CMakeLists.txt Visual Studio автоматически перезапускает шаг настройки CMake. When significant changes are made to the CMakeSettings.json or to CMakeLists.txt files, Visual Studio automatically reruns the CMake configure step. Если шаг настройки завершается без ошибок, собранные данные становятся доступны в C++ IntelliSense и языковых службах. If the configure step finishes without errors, the information that’s collected is available in C++ IntelliSense and language services. Они также используются в операциях сборки и отладки. It’s also used in build and debug operations.

Несколько проектов CMake могут использовать одно и то же имя конфигурации CMake (например, x86-Debug). Multiple CMake projects may use the same CMake configuration name (for example, x86-Debug). При выборе этой конфигурации все они настраиваются и собираются (в собственной корневой папке сборки). All of them are configured and built (in their own build root folder) when that configuration is selected. Вы можете отлаживать целевые объекты изо всех проектов CMake, участвующих в этой конфигурации CMake. You can debug the targets from all of the CMake projects that participate in that CMake configuration.

![Пункт меню «Только сборка CMake»](media/cmake-build-only.png «Пункт меню «Только сборка CMake»»)

Можно ограничить сеансы сборки и отладки подмножеством проектов в рабочей области. You can limit builds and debug sessions to a subset of the projects in the workspace. Создайте новую конфигурацию с уникальным именем в файле CMakeSettings.json. Create a new configuration with a unique name in the CMakeSettings.json file. Затем примените конфигурацию только к этим проектам. Then, apply the configuration to those projects only. При выборе этой конфигурации IntelliSense, а также команды сборки и отладки применяются только для указанных проектов. When that configuration is selected, IntelliSense and the build and debug commands only apply to those specified projects.

Устранение ошибок кэша CMake Troubleshooting CMake cache errors

Если вам нужны дополнительные сведения о состоянии кэша CMake для диагностики проблемы, откройте главное меню CMake или контекстное меню CMakeLists.txt в обозревателе решений, чтобы выполнить одну из следующих команд: If you need more information about the state of the CMake cache to diagnose a problem, open the CMake main menu or the CMakeLists.txt context menu in Solution Explorer to run one of these commands:

Просмотреть кэш открывает файл CMakeCache.txt из корневой папки сборки в редакторе. View Cache opens the CMakeCache.txt file from the build root folder in the editor. (Любые внесенные здесь изменения в CMakeCache.txt удаляются при очистке кэша. (Any edits you make here to CMakeCache.txt are wiped out if you clean the cache. Сведения о внесении изменений, сохраняемых после очистки кэша, см. в разделе Настройка параметров CMake.) To make changes that persist after the cache is cleaned, see Customize CMake settings.)

Открыть папку кэша открывает окно проводника с корневой папкой сборки. Open Cache Folder opens an Explorer window to the build root folder.

Очистить кэш удаляет корневую папку сборки, чтобы следующий шаг настройки CMake начинался с очистки кэша. Clean Cache deletes the build root folder so that the next CMake configure step starts from a clean cache.

Создать кэш принудительно создает шаг для выполнения, даже если Visual Studio считает среду актуальной. Generate Cache forces the generate step to run even if Visual Studio considers the environment up to date.

Вы можете отключить автоматическое создание кэша в диалоговом окне Сервис > Параметры > CMake > Общие. Automatic cache generation can be disabled in the Tools > Options > CMake > General dialog.

Компиляция одного файла Single file compilation

Для сборки отдельного файла в проекте CMake щелкните правой кнопкой мыши файл в обозревателе решений. To build a single file in a CMake project, right-click on the file in Solution Explorer. Выберите Компилировать во всплывающем меню. Choose Compile from the pop-up menu. Вы также можете скомпилировать открытый в редакторе файл через главное меню CMake: You can also build the currently open file in the editor by using the main CMake menu:

Запуск CMake из командной строки Run CMake from the command line

Если вы установили CMake из Visual Studio Installer, можете запустить это средство из командной строки, сделав следующее: If you have installed CMake from the Visual Studio Installer, you can run it from the command line by following these steps:

Запустите соответствующий файл vsdevcmd.bat (x86 или x64). Run the appropriate vsdevcmd.bat (x86/x64). Дополнительные сведения см. в статье Сборка из командной строки. For more information, see Building on the command line .

Перейдите в папку выходных данных. Switch to your output folder.

Запустите CMake для создания или настройки приложения. Run CMake to build/configure your app.

В Visual Studio 2015 пользователи Visual Studio могут использовать генератор CMake для создания файлов проекта MSBuild, которые интегрированная среда разработки использует для IntelliSense, просмотра и компиляции. In Visual Studio 2015, Visual Studio users can use a CMake generator to generate MSBuild project files, which the IDE then consumes for IntelliSense, browsing, and compilation.

Оцените статью