Clang install on windows

Clang/LLVM Support in Visual Studio

April 24th, 2019

Visual Studio 2019 version 16.1 Preview 2 comes with support for Clang/LLVM out-of-the-box. Visual Studio has had great tooling for MSVC and GCC for quite a while now. The latest preview brings Clang into the fold.

Visual Studio 2019 includes out of the box support for editing, building, and debugging CMake projects with Clang/LLVM. If you use MSBuild projects, however, don’t worry. Support for MSBuild based .vcxproj projects is coming soon as well. If you are not familiar with Visual Studio’s CMake, support check out how to get started.

If you are developing on Windows and targeting Clang, we hope to make Visual Studio the best IDE for that job. Please try out the preview and let us know what is working well and what isn’t.

Installing Clang/LLVM for use with Visual Studio

The “Desktop development with C++” workload with the Visual Studio installer now includes full support for targeting Clang/LLVM based toolsets. You will also need the actual compiler and tools to build your projects.

Getting Clang on Windows

On Windows, it’s easy to install the Clang tools. Just grab the “Clang compiler for Windows,” an optional component of the “Desktop development with C++” workload. This will install everything you need to develop with Clang on Windows.

You can also install your own copy of Clang/LLVM or even build it from source. If you have already installed Clang/LLVM you don’t need to install the compiler again with the Visual Studio installer. We do recommend that you use the most recent version of Clang to get the best support in the IDE. Older versions may have some limitations. Check out “Using a Custom Version of Clang” below for more information.

Getting Clang on Linux

To use Clang/LLVM on a remote Linux machine with Visual Studio, just install it with your distribution’s package manager. If ‘which clang’ finds the compiler you are good to go.

Getting Started with Clang/LLVM in Visual Studio

Once you have installed Clang, using it with CMake projects is easy. Visual Studio will use the MSVC compiler by default on Windows. On Linux, it will use the distribution’s default compiler, often GCC. To use Clang instead, add a configuration and select one of the Clang presets.

Select “Manage Configurations” from the configuration drop down on the left of the play button. Then click the “Add Configuration” button:

Another option is to modify an existing configuration with the CMake Settings editor to use any of the “clang” toolsets with the Toolset dropdown:

These toolsets will use Clang in clang-cl mode by default on Windows and link with the Microsoft STL. If you are targeting Linux, they will use Clang in GCC compatibility mode. Toolsets to build both 32 and 64-bit binaries are available on Windows while the Linux toolsets will target the architecture of the remote machine. Most of this behavior can be tweaked by customizing either the CMake command line or in the CMake project itself.

Edit, Build, and Debug

Once you have set up a Clang configuration, build and debug work exactly as you would expect in the IDE. Visual Studio will automatically detect that you are using the Clang compiler and provide applicable IntelliSense, highlighting, navigation, and other editing features. Building projects should just work, provided they are compatible with Clang, with any errors or warnings being directed to the Output Window.

Whether you are targeting Windows or Linux, the debugging experience with Clang should be familiar to you. Most of Visual Studio’s debugging features also work with Clang. There are just a few exceptions for compiler dependent features (e.g. edit and continue.) Breakpoints, memory and data visualization, and other inner development loop debugging features are available:

Using a Custom Installation of Clang

Visual Studio will automatically look for Clang in two places:

  1. (Windows) The internally installed copy of Clang/LLVM that comes with the Visual Studio installer.
  2. (Windows and Linux) The PATH environment variable.

If it doesn’t find Clang in one of those places it will offer to install it on Windows. On Linux, you will need to install it with the distribution’s package manager. Alternatively, you can tell Visual Studio to use another installation of Clang/LLVM on the machine by setting the “CMAKE_C_COMPILER” and “CMAKE_CXX_COMPILER” CMake variables in your CMake Settings:

Keep in mind, however, that using old versions of Clang may come with some limitations. For instance, if you are using the Microsoft STL on Windows, support is only gaurenteed for the most recent version of the compiler. As we release new versions of Visual Studio and the Microsoft STL you may need to upgrade your custom installation.

Читайте также:  Windows 10 долго грузиться профиль

Using Clang/LLVM with MSBuild Projects

Visual Studio 2019 version 16.1 ships with out of the box support for Clang/LLVM for CMake projects. Support for MSBuild based C++ projects is on the roadmap and will be available soon in a future release. To use Clang/LLVM today with MSBuild based C++ projects there are 3 rd party extensions for Visual Studio available.

Setting up the Clang Compiler in CLion on Windows

With CMake 3.15 it has become possible to use the Clang compiler on Windows with a GNU-style command line. This also means that it’s possible to use Clang with the Mingw-w64 toolchain.

While it’s possible to configure Clang with the Mingw-w64 (or MinGW) toolchain, if you decide to use Clang from the LLVM repo, it won’t work correctly. This is because LLVM Clang for Windows is built using Microsoft Visual Studio, and all the built-in macros and include search paths are set up for use with Visual Studio. So even when used with the MinGW toolchain, it will still try to include MSVC standard library headers.

We’ve done some experiments and found a possible workflow that involves using CLion in combination with the MinGW toolchain and Clang compiler.

Here are our findings:

  1. Install MSYS2 from https://www.msys2.org, follow their installation guide.
  2. Get the necessary packages with the pacman tool. We installed the following (pacman -S):
  • mingw-w64-x86_64-gcc
  • mingw-w64-x86_64-clang
  • mingw-w64-x86_64-lld
  • mingw-w64-x86_64-gdb
  • mingw-w64-x86_64-make
  • mingw-w64-x86_64-polly
  • mingw-w64-x86_64-compiler-rt

This clang compiler is built with mingw-w64 and has paths and macros that correspond to this toolchain.

Now we are ready to set up the CLion toolchain. Go to Settings/Preferences | Build, Execution, Deployment | Toolchains:

With your new toolchain configured, you can start building your project. You can use either the default ld linker or set the lld with -DCMAKE_LINKER=lld .

Using advanced tools provided by the Clang compiler

In theory, all Clang tools should also work without any issues. However, problems can arise involving compiler-rt. compiler-rt is a set of runtime libraries which are required to use sanitizers and profiling in Clang, the current compiler_rt package was built with MinGW. But Clang requires a compiler that is built with Clang and lld.

In our case, we wanted to use profile-guided optimization. One of the options for making this work is to get the compiler-rt source code of exactly the same version as the Clang version in MSYS2. This can be challenging, so the other solution is to clone the LLVM monorepo and build the tools you need.

For -fprofile-instr-generate it might be enough to build only compiler-rt and llvm-profdata to merge the profiler results. However, to use all the tools reliably, it’s better to build Clang and lld, as well.

Luckily we already have the required setup for that build.

The last step is to replace the binaries in \mingw64\lib\clang\ \lib\windows with libraries from \cmake-build-release-mingw_clang\lib\windows or from \lib\clang\ \lib\windows in case of monorepo.

Using Clang for profiling

With the compiler-rt libraries in place, it’s now possible to use the same toolchain we set up with -fprofile-instr-generate/-fprofile-instr-use flags. Let’s build LLVM for this experiment, since we already have the source code. We’ll also use -DLLVM_ENABLE_LTO=Thin for even more optimization. Go to Settings/Preferences | Build, Execution, Deployment | CMake:

With this CMake configuration, you can build the Clang compiler and use it, for example, to build your own project. This will generate the relevant profiler information, which should later be merged with the tool we built earlier – llvm-profdata. With the merged profile_merged.profdata file, you can finally build the optimized version of the Clang compiler:

Using custom Clang and lld

Getting the gcc-style -fprofile-generate/-fprofile-use flags to work correctly requires changing the Clang path and setting -DCMAKE_LINKER to the newly built lld. You also need a few additional tricks for LLVM : -femulated-tls and linking pthread.

Then you should repeat all the steps you performed with -fprofile-instr-generate/-fprofile-instr-use.

Conclusion

Using Clang on Windows is now possible and does not require you to have Microsoft Visual Studio installed!

We hope that in the near future, using advanced clang tools will become easier and will no longer require the manual build. Let us know if you discover any other ways to achieve the same results!

Your CLion team
JetBrains
The Drive to Develop

Installing clang++ to compile and link on Windows : Part 3

01 Sep 2015

Part 1 : The Problem
Part 2 : Approach 1 — Clang 3.7
Part 3 : Approach 2 — MSYS2

Approach 2 — MSYS2

In this approach we’ll be installing MSYS2 to create a unix-like dev environment on windows that we will install clang and gcc on. That dev environment will then be interacted with through its bash shell.

  1. Download and install MSYS2 64 bit: Download Link (you’d basically never need to download the 32 bit version, since the 64 bit version can install 32 bit packages)
  2. After the installer completes and the MSYS2 shell appears (to re-open it, the batch file is located in C:\msys64\msys2_shell.bat ). We Need to update its packages:
    • First, update the core packages: pacman —needed -Sy bash pacman pacman-mirrors msys2-runtime . Enter ‘y’ when prompted and the updates may take a few minutes.
    • IMPORTANT: close the shell and re-open it here before doing anything else.
    • Now we can update all packages with: pacman -Su
    • For more detailed information on MSYS2’s package management see sections 3-5 in the documentation
  3. Install the 32 bit version of MinGW-w64 and Clang (currently gcc is version 5.2.0 and clang is version 3.6.2): pacman -S mingw-w64-x86_64-clang mingw-w64-i686-clang
  4. Similar to cygwin, the windows path C:\ drive maps to the directory /c in MSYS2.
Читайте также:  Как вызвать настройки системы windows

Using MSYS2 to compile with Clang/GCC

To use the 64 bit versions of clang/clang++/gcc/g++, launch the 64 bit shell batch file, located at C:\msys64\mingw64_shell.bat and for the 32 bit versions use C:\msys64\mingw32_shell.bat .

  • so you can use them from the commandline it may make sense to add C:\msys64 to your system PATH.

Поддержка 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:

  1. Щелкните правой кнопкой мыши узел проекта в обозревателе решений и выберите пункт Свойства. Right-click on the project node in Solution Explorer and choose Properties.
  2. Как правило, сначала следует выбрать элемент Все конфигурации в верхней части диалогового окна. Typically, you should first choose All configurations at the top of the dialog.
  3. В разделе Общие >Набор инструментов платформы выберите 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.
  4. Нажмите кнопку ОК. 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.

Читайте также:  Как добавить постоянный маршрут windows

Задание настраиваемого расположения 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.

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