- Поддержка Clang и LLVM в проектах Visual Studio Clang/LLVM support in Visual Studio projects
- Установка Install
- Настройка проекта Windows для использования средств Clang Configure a Windows project to use Clang tools
- Настройка проекта Linux для использования средств Clang Configure a Linux project to use Clang tools
- Задание настраиваемого расположения LLVM Set a custom LLVM location
- Задание пользовательской версии набора инструментов LLVM Set a custom LLVM toolset version
- Настройка дополнительных свойств, изменение, сборка и отладка Set additional properties, edit, build, and debug
- InNoHurryToCode / ClangOnWindows.md
Поддержка Clang и LLVM в проектах Visual Studio Clang/LLVM support in Visual Studio projects
В Visual Studio 2019 доступна поддержка Clang для проектов CMake и MSBuild. Clang support for both CMake and MSBuild projects is available in Visual Studio 2019.
Visual Studio 2019 версии 16.2 и более поздних версий с Clang можно использовать для изменения, сборки и отладки проектов Visual Studio на C++ (MSBuild), предназначенных для Windows или Linux. You can use Visual Studio 2019 version 16.2 and later with Clang to edit, build, and debug C++ Visual Studio projects (MSBuild) that target Windows or Linux.
Установка Install
Для лучшей поддержки интегрированной среды разработки в Visual Studio рекомендуется использовать новейшие средства компилятора Clang для Windows. For best IDE support in Visual Studio, we recommend using the latest Clang compiler tools for Windows. Если они еще не установлены, их можно установить, открыв Visual Studio Installer и выбрав Средства C++ Clang для Windows в разделе дополнительных компонентов Разработка классических приложений на C++ . If you don’t already have the tools, you can install them by opening the Visual Studio Installer and choosing C++ Clang tools for Windows under Desktop development with C++ optional components. Если вы предпочитаете использовать существующую установку Clang на компьютере, выберите необязательный компонент Средства сборки C++ Clang-cl для версии 142. You may prefer to use an existing Clang installation on your machine; if so, choose the C++ Clang-cl for v142 build tools. . optional component.
Для стандартной библиотеки Microsoft C++ требуется по крайней мере Clang 8.0.0. The Microsoft C++ Standard Library requires at least Clang 8.0.0.
В позднейших версиях Visual Studio предоставляются более новые версии набора инструментов Clang. Later versions of Visual Studio provide newer versions of the Clang toolset. Пакетная версия Clang обновляется автоматически, чтобы оставаться актуальной с учетом обновлений в реализации стандартной библиотеки Майкрософт. The bundled version of Clang gets updated automatically to stay current with updates in the Microsoft implementation of the Standard Library. Например, Visual Studio 2019 версии 16.9 включает Clang версии 11. For example, Visual Studio 2019 version 16.9 includes Clang v11.
Настройка проекта Windows для использования средств Clang Configure a Windows project to use Clang tools
Чтобы настроить использование Clang в проекте Visual Studio, в обозревателе решений щелкните узел проекта правой кнопкой мыши и выберите пункт Свойства. To configure a Visual Studio project to use Clang, right-click on the project node in Solution Explorer and choose Properties. Как правило, сначала следует выбрать элемент Все конфигурации в верхней части диалогового окна. Typically, you should first choose All configurations at the top of the dialog. Затем в разделе Общие > Набор инструментов платформы выберите LLVM (clang-cl) и нажмите кнопку ОК. Then, under General > Platform Toolset, choose LLVM (clang-cl) and then OK.
«Общие» и выделенными пунктами «Набор средств платформы» и «LLVM (clang-cl)».» data-linktype=»relative-path»>
Если вы используете средства Clang, входящие в состав Visual Studio, никаких дополнительных действий не требуется. If you’re using the Clang tools that are bundled with Visual Studio, no extra steps are required. Для проектов Windows программа Visual Studio по умолчанию вызывает Clang в режиме clang-cl. For Windows projects, Visual Studio by default invokes Clang in clang-cl mode. Он связывается с реализацией стандартной библиотеки Майкрософт. It links with the Microsoft implementation of the Standard Library. По умолчанию clang-cl.exe находится в каталогах %VCINSTALLDIR%\Tools\Llvm\bin\ и %VCINSTALLDIR%\Tools\Llvm\x64\bin\ . By default, clang-cl.exe is located in %VCINSTALLDIR%\Tools\Llvm\bin\ and %VCINSTALLDIR%\Tools\Llvm\x64\bin\.
Если используется настраиваемая установка Clang, можно изменить свойство Проект > Свойства > Каталоги VC++ > Свойства конфигурации > Каталоги исполняемых файлов, добавив корневой каталог настраиваемой установки Clang в качестве первого каталога, или изменить значение свойства LLVMInstallDir . If you’re using a custom Clang installation, you can either modify Project > Properties > VC++ DIrectories > Configuration Properties > Executable Directories by adding the custom Clang installation root as the first directory there, or change the value of the LLVMInstallDir property. Дополнительные сведения см. в разделе Задание настраиваемого расположения LLVM. For more information, see Set a custom LLVM location.
Настройка проекта Linux для использования средств Clang Configure a Linux project to use Clang tools
Для проектов Linux среда Visual Studio использует интерфейс, совместимый с Clang GCC. For Linux projects, Visual Studio uses the Clang GCC-compatible frontend. Свойства проекта и почти все флаги компилятора идентичны. The project properties and nearly all compiler flags are identical
Чтобы настроить использование Clang в проекте Visual Studio для Linux, выполните указанные ниже действия. To configure a Visual Studio Linux project to use Clang:
- Щелкните правой кнопкой мыши узел проекта в обозревателе решений и выберите пункт Свойства. Right-click on the project node in Solution Explorer and choose Properties.
- Как правило, сначала следует выбрать элемент Все конфигурации в верхней части диалогового окна. Typically, you should first choose All configurations at the top of the dialog.
- В разделе Общие >Набор инструментов платформы выберите WSL_Clang_1_0, если вы используете подсистему Windows для Linux (WSL). Under General >Platform Toolset, choose WSL_Clang_1_0 if you’re using Windows Subsystem for Linux (WSL). Выберите Remote_Clang_1_0, если вы используете удаленный компьютер или виртуальную машину. Choose Remote_Clang_1_0 if you’re using a remote machine or VM.
- Нажмите кнопку ОК. Press OK.
«Общие» и выделенными пунктами «Набор средств платформы» и «LLVM (clang-cl)».» data-linktype=»relative-path»>
В Linux среда Visual Studio по умолчанию использует первое расположение Clang, которое встречается в свойстве среды PATH. On Linux, Visual Studio by default uses the first Clang location that it finds in the PATH environment property. Если используется настраиваемая установка Clang, измените значение свойства LLVMInstallDir или подставьте путь в свойстве Проект > Свойства > Свойства конфигурации > Каталоги VC++ > Каталоги исполняемых файлов. If you’re using a custom Clang installation, then either change the value of the LLVMInstallDir property or else enter the path under Project > Properties > Configuration Properties > VC++ DIrectories > Executable Directories. Дополнительные сведения см. в разделе Задание настраиваемого расположения LLVM. For more information, see Set a custom LLVM location.
Задание настраиваемого расположения LLVM Set a custom LLVM location
Можно задать настраиваемый путь к LLVM для одного или нескольких проектов, создав файл Directory.build.props. You can set a custom path to LLVM for one or more projects by creating a Directory.build.props file. Затем добавьте этот файл в корневую папку любого проекта. Then, add that file to the root folder of any project. Его можно добавить в корневую папку решения, чтобы применить его ко всем проектам в решении. You can add it to the root solution folder to apply it to all projects in the solution. Файл должен выглядеть следующим образом (только с фактическим путем LLVM): The file should look like this (but use your actual LLVM path):
Это свойство можно объединить с пользовательской версией набора инструментов LLVM. You can combine this property with a custom LLVM toolset version. Дополнительные сведения см. в разделе Установка пользовательской версии набора инструментов LLVM. For more information, see Set a custom LLVM toolset version.
Задание пользовательской версии набора инструментов LLVM Set a custom LLVM toolset version
Начиная с Visual Studio 2019 версии 16.9, можно задать пользовательскую версию набора инструментов для LLVM. Starting in Visual Studio 2019 version 16.9, you can set a custom toolset version for LLVM. Чтобы задать это свойство в проекте в Visual Studio, выполните следующие действия: To set this property in a project in Visual Studio:
Откройте диалоговое окно Страницы свойств проекта. Open the project’s Property Pages dialog box. Подробнее см. в статье Настройка компилятора C++ и свойства сборки в Visual Studio. For details, see Set C++ compiler and build properties in Visual Studio.
Перейдите на страницу свойств Свойства конфигурации > Общие. Select the Configuration Properties > General property page.
Измените значение свойства Набор инструментов платформы на LLVM (clang-cl) , если оно еще не задано. Modify the Platform Toolset property to LLVM (clang-cl), if it isn’t already set.
Перейдите на страницу свойств Свойства конфигурации > Расширенные. Select the Configuration Properties > Advanced property page.
Измените свойство Версия инструментов LLVM на предпочитаемую версию, а затем нажмите кнопку ОК, чтобы сохранить изменения. Modify the LLVM Toolset Version property to your preferred version, and then choose OK to save your changes.
Свойство Версия набора инструментов LLVM отображается только при выборе набора инструментов платформы LLVM. The LLVM Toolset Version property only appears when the LLVM platform toolset is selected.
Версию набора инструментов можно задать для одного или нескольких проектов, создав файл Directory.build.props. You can set the toolset version for one or more projects by creating a Directory.build.props file. Затем добавьте этот файл в корневую папку любого проекта. Then, add that file to the root folder of any project. Добавьте его в корневую папку решения, чтобы применить его ко всем проектам в решении. Add it to the root solution folder to apply it to all projects in the solution. Файл должен выглядеть следующим образом (только с фактическим путем LLVM): The file should look like this (but use your actual LLVM path):
Это свойство также можно объединить с пользовательским расположением LLVM. You can also combine this property with a custom LLVM location. Например, файл Directory.build.props может выглядеть следующим образом: For example, your Directory.build.props file could look like:
При добавлении файла Directory.build.props параметры отображаются по умолчанию в диалоговом окне страницы свойств проекта. When you add a Directory.build.props file, the settings appear as the default in the project Property Pages dialog. Однако при изменении этих свойств в Visual Studio они переопределяют параметры в файле Directory.build.props. However, changes to these properties in Visual Studio override the settings in the Directory.build.props file.
Настройка дополнительных свойств, изменение, сборка и отладка Set additional properties, edit, build, and debug
После настройки конфигурации Clang снова щелкните правой кнопкой мыши узел проекта и выберите пункт Перезагрузить проект. After you have set up a Clang configuration, right-click again on the project node and choose Reload project. Теперь можно выполнять сборку и отладку проекта с помощью средств Clang. You can now build and debug the project using the Clang tools. Visual Studio обнаруживает, что используется компилятор Clang, и предоставляет IntelliSense, выделение, навигацию и другие функции редактирования. Visual Studio detects that you’re using the Clang compiler and provides IntelliSense, highlighting, navigation, and other editing features. Ошибки и предупреждения отображаются в окне вывода. Errors and warnings are displayed in the Output Window. Страницы свойств проекта для конфигурации Clang похожи на параметры для MSVC. The project property pages for a Clang configuration are similar to the ones for MSVC. Однако некоторые зависящие от компилятора функции, такие как «Изменить и продолжить», недоступны для конфигураций Clang. However, some compiler-dependent features such as Edit and Continue aren’t available for Clang configurations. Можно задать компилятор Clang или параметр компоновщика, который недоступен на страницах свойств. You can set a Clang compiler or linker option that isn’t available in the property pages. Добавьте его вручную на страницах свойств в разделе Свойства конфигурации > C/ C++ (или «Компоновщик») > Командная строка > Дополнительные параметры. Add it manually in the property pages under Configuration Properties > C/C++ (or Linker) > Command Line > Additional Options.
При отладке можно использовать точки останова, память и визуализацию данных, а также большинство других функций отладки. When debugging, you can use breakpoints, memory and data visualization, and most other debugging features.
InNoHurryToCode / ClangOnWindows.md
Clang on Windows (VS 2017 build tools)
There are plenty of tutorials online on how to install clang on windows with visual studioIDE and MinGW. However, there are none on clang with visual studio build tools.
- 64-bit Windows 7 SP1 or newer with the latest updates installed
- 6 GB of free space on the partition where Windows is installed
- internet connection (for installation only)
1. Install VS 2017 build tools
%VS2017BuildToolsDir% = installation directory of VS 2017 build tools
- download and run the microsoft visual studio build tools
- select and install the following individual component(s):
- Static analysis tools
- VC++ 2015.3 v140 toolset for desktop (x86,x64)
- VC++ 2017 v141 toolset (x86,x64)
- Visual C++ Build Tools core features
- Windows Universal C Runtime
- if windows 10:
- Windows 10 SDK (10.0.10240.0)
- if windows 7 / 8 / 8.1
- Windows Universal CRT SDK
- Windows 8.1 SDK
- Start > Visual Studio 2017 > Developer Command Prompt for VS 2017 (run as administrator)
- execute command(s):
- download and run LLVM
- add to PATH for current/all user(s)
3. Remove redulant files
- run visual studio installer
- remove the following individual component(s):
- VC++ 2015.3 v140 toolset for desktop (x86,x64)
%procdir% = directory where you created proc.c
- Start > Windows System > Command Prompt (run as administrator)
- execute command(s):
You didn’t select the set PATH for current/all user(s). If you did but it still didn’t work, set the path environment variable manually by adding %LLVMInstallLocation%\bin
You didn’t install VC++ 2015.3 v140 toolset for desktop (x86,x64) and/or VC++ 2017 v141 toolset and/or run VsMSBuildCmd