Как установить компилятор msvc
Перейти к содержимому

Как установить компилятор msvc

  • автор:

Установка MSVC без Visual Studio

Можно ли установить минимальное окружение для компиляции свежим компилятором MSVC (x64 msvc v19.24 или новее) из командной строки, не скачивая и/или устанавливая Visual Studio? Если да, то как?

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

dIm0n's user avatar

Да, вы можете скачать с официального сайта microsoft BuiltTools от нужной вам Visual Studio. Также эти инструменты можно подключить например к VSCode. Подробная инструкция в разрезе установки BuildTools и подключению к VSCode здесь.

Configure VS Code for Microsoft C++

In this tutorial, you configure Visual Studio Code to use the Microsoft Visual C++ compiler and debugger on Windows.

After configuring VS Code, you will compile and debug a simple Hello World program in VS Code. This tutorial does not teach you details about the Microsoft C++ toolset or the C++ language. For those subjects, there are many good resources available on the Web.

If you have any problems, feel free to file an issue for this tutorial in the VS Code documentation repository.


To successfully complete this tutorial, you must do the following:

Install the C/C++ extension for VS Code. You can install the C/C++ extension by searching for ‘c++’ in the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ).

C/C++ extension

Install the Microsoft Visual C++ (MSVC) compiler toolset.

If you have a recent version of Visual Studio, open the Visual Studio Installer from the Windows Start menu and verify that the C++ workload is checked. If it’s not installed, then check the box and select the Modify button in the installer.

You can also install the Desktop development with C++ workload without a full Visual Studio IDE installation. From the Visual Studio Downloads page, scroll down until you see Tools for Visual Studio under the All Downloads section and select the download for Build Tools for Visual Studio 2022.

Build Tools for Visual Studio download

This will launch the Visual Studio Installer, which will bring up a dialog showing the available Visual Studio Build Tools workloads. Check the Desktop development with C++ workload and select Install.

Cpp build tools workload

Note: You can use the C++ toolset from Visual Studio Build Tools along with Visual Studio Code to compile, build, and verify any C++ codebase as long as you also have a valid Visual Studio license (either Community, Pro, or Enterprise) that you are actively using to develop that C++ codebase.

Check your Microsoft Visual C++ installation

To use MSVC from a command line or VS Code, you must run from a Developer Command Prompt for Visual Studio. An ordinary shell such as PowerShell, Bash, or the Windows command prompt does not have the necessary path environment variables set.

To open the Developer Command Prompt for VS, start typing ‘developer’ in the Windows Start menu, and you should see it appear in the list of suggestions. The exact name depends on which version of Visual Studio or the Visual Studio Build Tools you have installed. Select the item to open the prompt.

Developer Command Prompt

You can test that you have the C++ compiler, cl.exe , installed correctly by typing ‘cl’ and you should see a copyright message with the version and basic usage description.

Checking cl.exe installation

If the Developer Command Prompt is using the BuildTools location as the starting directory (you wouldn’t want to put projects there), navigate to your user folder ( C:\users\\ ) before you start creating new projects.

Note: If for some reason you can’t run VS Code from a Developer Command Prompt, you can find a workaround for building C++ projects with VS Code in Run VS Code outside a Developer Command Prompt.

Create Hello World

From the Developer Command Prompt, create an empty folder called "projects" where you can store all your VS Code projects, then create a subfolder called "helloworld", navigate into it, and open VS Code ( code ) in that folder ( . ) by entering the following commands:

The "code ." command opens VS Code in the current working folder, which becomes your "workspace". As you go through the tutorial, you will see three files created in a .vscode folder in the workspace:

  • tasks.json (build instructions)
  • launch.json (debugger settings)
  • c_cpp_properties.json (compiler path and IntelliSense settings)

Add a source code file

In the File Explorer title bar, select the New File button and name the file helloworld.cpp .

Add hello world source code

Now paste in this source code:

Now press ⌘S (Windows, Linux Ctrl+S ) to save the file. Notice how the file you just added appears in the File Explorer view ( ⇧⌘E (Windows, Linux Ctrl+Shift+E ) ) in the side bar of VS Code:

File Explorer

You can also enable Auto Save to automatically save your file changes, by checking Auto Save in the main File menu.

The Activity Bar on the far left lets you open different views such as Search, Source Control, and Run. You’ll look at the Run view later in this tutorial. You can find out more about the other views in the VS Code User Interface documentation.

Note: When you save or open a C++ file, you may see a notification from the C/C++ extension about the availability of an Insiders version, which lets you test new features and fixes. You can ignore this notification by selecting the X (Clear Notification).

Explore IntelliSense

In your new helloworld.cpp file, hover over vector or string to see type information. After the declaration of the msg variable, start typing msg. as you would when calling a member function. You should immediately see a completion list that shows all the member functions, and a window that shows the type information for the msg object:

Statement completion IntelliSense

You can press the Tab key to insert the selected member; then, when you add the opening parenthesis, you will see information about any arguments that the function requires.

Run helloworld.cpp

Remember, the C++ extension uses the C++ compiler you have installed on your machine to build your program. Make sure you have a C++ compiler installed before attempting to run and debug helloworld.cpp in VS Code.

Open helloworld.cpp so that it is the active file.

Press the play button in the top right corner of the editor.

Choose C/C++: cl.exe build and debug active file from the list of detected compilers on your system.

You’ll only be asked to choose a compiler the first time you run helloworld.cpp . This compiler will be set as the "default" compiler in tasks.json file.

After the build succeeds, your program’s output will appear in the integrated Terminal.

If you get an error trying to build and debug with cl.exe, make sure you have started VS Code from the Developer Command Prompt for Visual Studio using the code . shortcut.

The first time you run your program, the C++ extension creates tasks.json , which you’ll find in your project’s .vscode folder. tasks.json stores build configurations.

Your new tasks.json file should look similar to the JSON below:

Note: You can learn more about tasks.json variables in the variables reference.

The command setting specifies the program to run; in this case that is "cl.exe". The args array specifies the command-line arguments that will be passed to cl.exe. These arguments must be specified in the order expected by the compiler.

This task tells the C++ compiler to take the active file ( $ ), compile it, and create an executable file ( /Fe: switch) in the current directory ( $ ) with the same name as the active file but with the .exe extension ( $.exe ), resulting in helloworld.exe for our example.

The label value is what you will see in the tasks list; you can name this whatever you like.

The detail value is what you will as the description of the task in the tasks list. It’s highly recommended to rename this value to differentiate it from similar tasks.

The problemMatcher value selects the output parser to use for finding errors and warnings in the compiler output. For cl.exe, you’ll get the best results if you use the $msCompile problem matcher.

From now on, the play button will read from tasks.json to figure out how to build and run your program. You can define multiple build tasks in tasks.json , and whichever task is marked as the default will be used by the play button. In case you need to change the default compiler, you can run Tasks: Configure default build task. Alternatively you can modify the tasks.json file and remove the default by replacing this segment:

Modifying tasks.json

You can modify your tasks.json to build multiple C++ files by using an argument like "$/*.cpp" instead of $ .This will build all .cpp files in your current folder. You can also modify the output filename by replacing "$\\$.exe" with a hard-coded filename (for example "$\\myProgram.exe" ).

Debug helloworld.cpp

  1. Go back to helloworld.cpp so that it is the active file.
  2. Set a breakpoint by clicking on the editor margin or using F9 on the current line.
  3. From the drop-down next to the play button, select Debug C/C++ File.
  4. Choose C/C++: cl.exe build and debug active file from the list of detected compilers on your system (you’ll only be asked to choose a compiler the first time you run/debug helloworld.cpp ).

The play button has two modes: Run C/C++ File and Debug C/C++ File. It will default to the last-used mode. If you see the debug icon in the play button, you can just click the play button to debug, instead of selecting the drop-down menu item.

If you get an error trying to build and debug with cl.exe, make sure you have started VS Code from the Developer Command Prompt for Visual Studio using the code . shortcut.

Explore the debugger

Before you start stepping through the code, let’s take a moment to notice several changes in the user interface:

The Integrated Terminal appears at the bottom of the source code editor. In the Debug Output tab, you see output that indicates the debugger is up and running.

The editor highlights the line where you set a breakpoint before starting the debugger:

The Run and Debug view on the left shows debugging information. You’ll see an example later in the tutorial.

At the top of the code editor, a debugging control panel appears. You can move this around the screen by grabbing the dots on the left side.

Debugging controls

Step through the code

Now you’re ready to start stepping through the code.

Click or press the Step over icon in the debugging control panel.

This will advance program execution to the first line of the for loop, and skip over all the internal function calls within the vector and string classes that are invoked when the msg variable is created and initialized. Notice the change in the Variables window on the left.

Debugging windows

In this case, the errors are expected because, although the variable names for the loop are now visible to the debugger, the statement has not executed yet, so there is nothing to read at this point. The contents of msg are visible, however, because that statement has completed.

Press Step over again to advance to the next statement in this program (skipping over all the internal code that is executed to initialize the loop). Now, the Variables window shows information about the loop variables.

Press Step over again to execute the cout statement. (Note that as of the March 2019 release, the C++ extension does not print any output to the Debug Console until the loop exits.)

If you like, you can keep pressing Step over until all the words in the vector have been printed to the console. But if you are curious, try pressing the Step Into button to step through source code in the C++ standard library!

Breakpoint in gcc standard library header

To return to your own code, one way is to keep pressing Step over. Another way is to set a breakpoint in your code by switching to the helloworld.cpp tab in the code editor, putting the insertion point somewhere on the cout statement inside the loop, and pressing F9 . A red dot appears in the gutter on the left to indicate that a breakpoint has been set on this line.

Breakpoint in main

Then press F5 to start execution from the current line in the standard library header. Execution will break on cout . If you like, you can press F9 again to toggle off the breakpoint.

Set a watch

Sometimes you might want to keep track of the value of a variable as your program executes. You can do this by setting a watch on the variable.

Place the insertion point inside the loop. In the Watch window, select the plus sign and in the text box, type word , which is the name of the loop variable. Now view the Watch window as you step through the loop.

Watch window

Add another watch by adding this statement before the loop: int i = 0; . Then, inside the loop, add this statement: ++i; . Now add a watch for i as you did in the previous step.

To quickly view the value of any variable while execution is paused on a breakpoint, you can hover over it with the mouse pointer.

Mouse hover

Customize debugging with launch.json

When you debug with the play button or F5 , the C++ extension creates a dynamic debug configuration on the fly.

There are cases where you’d want to customize your debug configuration, such as specifying arguments to pass to the program at runtime. You can define custom debug configurations in a launch.json file.

To create launch.json , choose Add Debug Configuration from the play button drop-down menu.

You’ll then see a dropdown for various predefined debugging configurations. Choose C/C++: cl.exe build and debug active file.

VS Code creates a launch.json file, which looks something like this:

In the JSON above, program specifies the program you want to debug. Here it is set to the active file folder ( $ ) and active filename with the .exe extension ( $.exe ), which if helloworld.cpp is the active file will be helloworld.exe . The args property is an array of arguments to pass to the program at runtime.

By default, the C++ extension won’t add any breakpoints to your source code and the stopAtEntry value is set to false .

Change the stopAtEntry value to true to cause the debugger to stop on the main method when you start debugging.

From now on, the play button and F5 will read from your launch.json file when launching your program for debugging.

C/C++ configurations

If you want more control over the C/C++ extension, you can create a c_cpp_properties.json file, which will allow you to change settings such as the path to the compiler, include paths, C++ standard (default is C++17), and more.

You can view the C/C++ configuration UI by running the command C/C++: Edit Configurations (UI) from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ).

Command Palette

This opens the C/C++ Configurations page. When you make changes here, VS Code writes them to a file called c_cpp_properties.json in the .vscode folder.

Command Palette

Visual Studio Code places these settings in .vscode\c_cpp_properties.json . If you open that file directly, it should look something like this:

You only need to add to the Include path array setting if your program includes header files that are not in your workspace or in the standard library path.

Compiler path

The compilerPath setting is an important setting in your configuration. The extension uses it to infer the path to the C++ standard library header files. When the extension knows where to find those files, it can provide useful features like smart completions and Go to Definition navigation.

The C/C++ extension attempts to populate compilerPath with the default compiler location based on what it finds on your system. The extension looks in several common compiler locations.

The compilerPath search order is:

  • First check for the Microsoft Visual C++ compilerOpe
  • Then look for g++ on Windows Subsystem for Linux (WSL)
  • Then g++ for Mingw-w64.

If you have g++ or WSL installed, you might need to change compilerPath to match the preferred compiler for your project. For Microsoft C++, the path should look something like this, depending on which specific version you have installed: "C:/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools/VC/Tools/MSVC/14.16.27023/bin/Hostx64/x64/cl.exe".

Reusing your C++ configuration

VS Code is now configured to use the Microsoft C++ compiler. The configuration applies to the current workspace. To reuse the configuration, just copy the JSON files to a .vscode folder in a new project folder (workspace) and change the names of the source file(s) and executable as needed.

Run VS Code outside the Developer Command Prompt

In certain circumstances, it isn’t possible to run VS Code from Developer Command Prompt for Visual Studio (for example, in Remote Development through SSH scenarios). In that case, you can automate initialization of Developer Command Prompt for Visual Studio during the build using the following tasks.json configuration:

Note: The path to VsDevCmd.bat might be different depending on the Visual Studio version or installation path. You can find the path to VsDevCmd.bat by opening a Command Prompt and running dir "\VsDevCmd*" /s .


The term ‘cl.exe’ is not recognized

If you see the error "The term ‘cl.exe’ is not recognized as the name of a cmdlet, function, script file, or operable program.", this usually means you are running VS Code outside of a Developer Command Prompt for Visual Studio and VS Code doesn’t know the path to the cl.exe compiler.

VS Code must either be started from the Developer Command Prompt for Visual Studio, or the task must be configured to run outside a Developer Command Prompt.

Как установить компилятор msvc

Эта статья в основном изучает генерацию и анализ файлов дампа в операционной системе Windows, редактором QT, среды компиляции MSVC. В основном описание из следующих аспектов:

1. Значение файла дампа;

2. Настройте операционную систему Win10, QT + среда компиляции записи MSVC;

3. Как генерируется дамп файл;

4. Программное обеспечение Windows анализирует необходимые материалы для файлов отладки Dump: файл PDB;

5. Аналитические и методы отладки;

2. Цель

Почему вам нужно изучать анализ файла Dump?

После того, как программное обеспечение работает в течение длительного времени, вдруг вылетает или мертвы, а журналы в это время не написаны или любая информация не может быть запрошена в журнале. На данный момент нам необходимо проанализировать файл дампа, оцените стек, когда сбой, и отладка точки останова, чтобы просматривать соответствующее значение, а затем понять осторожный узел программного обеспечения и исправить его.

3. КТ + Конфигурация среды MSVC

Попробуйте загрузить компилятор MSCV с помощью Qt Self-detection.

3.1. Установите Qt

При установке Qt необходимо обратить внимание на установленную установку набора. Моя версия QT является Qt5.12.2. Выбор установленного комплекта имеет Qt 5.12.2 MSVC2015 64BIT, QT 5.12.2 MSVC2017 32-бит, Qt 5.12.2 MINGW 32 -Bit, Qt 5.12.2 MINGW 64-BIT. После завершения установки вы видите установленный комплект набора в Qt-> Tools -> Опции -> Комплекты. После завершения установки вы можете добавить путь, в котором компилятор находится в переменной среды.

3.2. Установите VS или установите соответствующую версию компилятора

Поскольку есть Qt 5.12.2 MSVC2017 32-битный при установке Qt, я выбираю для установки версии VS также является версией 2017 года (PS: Существует версия 2019 до того, что результат Qt не может естественным образом найти соответствующий компилятор, он должен быть Qt5. 12.2 Невозможно обнаружить компилятор VS2019, конечно, мы также можем определить компилятор в Qt, который не объясняется здесь. Выберите установленный контент, включая «Использование разработки настольных компьютеров C ++», «Разработка платформы GM Windows».

3. Настройте среду QT MSVC

После установки VS завершен, QT перезапускается, а соответствующий компилятор будет замечен в Qt-> Tools -> Параметры -> Комплекты.

Затем компилятор и отладчик будут настроен с комплектом Suite. Конфигурация Microsoft Microsoft Compiler.

На данный момент среда компиляции MSVC QT5.12 + завершена.

4. Создание файла дампа

4.1 Установка инструментов отладки Windows

Официальный веб-сайт загружает WIN10 SDK, устанавливает только инструменты отладки Windows. После завершения установки будут выполнены файлы, связанные с dpghelp. Программное обеспечение для отладки Windbg также установлено.

ссылка для скачивания:Win10SDK

4.2 QT генерирует код файла дампа

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

5. Дамп отладка QT Сырье: файл PDB

Если приложение или сервис генерирует файл PDB, вам нужно только добавить дополнительные параметры в qmake, построенный в проекте:

Тем не менее, QT Self-установка устанавливается при установке QT, поэтому нам нужно вручную установить файлы PDB Qt:

Установите вручную установить соответствующий файл PDBОригинальный адрес ссылки。

а) сначала найдите его в каталоге установки QtMaintenanceTool.exe, Запустить его

b) Установите адрес репозитория, рекомендуется выбрать временную библиотеку, добавить адрес, тестируйте и напомнить успеху, нажмите OK. (5122 — номер версии Qt)

c) Добавить или удалить компонент, нажмите «Далее».

d) Выберите «qt debug Информационные файлы». После выбора нажмите «Далее» и установите его. Если сеть медленная, это будет длительный процесс. (Примечание. Не удаляйте настройку, если вы не хотите удалить?)

На данный момент все конфигурации были завершены необходимые материалы. Далее — отлаживать содержимое отвала.

Добавление MSVC 2017 в Qt

Я перепробовал слишком много вещей. У меня есть длинная история с главной проблемой Qt! Моя основная проблема: «тип компьютера модуля« x64 »конфликтует с целевым компьютером« x86 »», который появляется в консоли при сборке приложения Qt! Я собираюсь включить некоторые из вещей, которые я попробовал: — Попытался собрать из приложения Qt и Консоли. — Перепробовал все компиляторы, которые автоматически определяются из Qt. Есть и другие, но не нужно упоминать об остальном. В моих наборах по умолчанию большинство имен были в следующем порядке: «Qt 5.13.0 для 64/86-бит UWP (MSVC 2017)». Я думал, что это должен быть MSVC 2017, поэтому я попытался настроить MSVC 2017 (у меня MSVC 2019). Я нашел основную программу компилятора, которая называется «cl.exe». Я пошел в автоопределенные компиляторы Qt, я не нашел это! Я попытался добавить его, скопировав команды для qmake.exe и jom.exe из другого набора, который уже сделан для меня. Тем не менее, я поставил тип компилятора ‘custom’, потому что я не нашел MSVC. Это неправильно, и чем это отличается от других типов?

Моя следующая вещь, чтобы исправить (на самом деле попробовать) это:


Рисунок выше содержит путь к компилятору и путь к Make. Мне нужно найти инструмент Make path, я думаю, что он необходим, не так ли? Я попытался запустить программу без шага Make, ТОЛЬКО qmake step. Это привело меня к другой проблеме при запуске программы: «Произошла ошибка при попытке построить / развернуть вашу программу». Я правильно заполнил путь к компилятору, но я не знаю, как заполнить путь создания, я даже не знаю, что такое путь создания. Обратите внимание, что Qt не дает мне никакого результата, потому что путь создания не заполнен правильно!

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

2 ответа

Вы не можете добавить MSVC вручную в Qt Creator. Вам нужно, чтобы он был автоматически обнаружен.

Также меняется механизм обнаружения в зависимости от версии MSVC и версии Qt Creator. Поэтому убедитесь, что вы используете последнюю версию Qt Creator (на данный момент 4.9.2), чтобы убедиться, что все ваши установленные инструменты MSVC обнаружены.

Также, учитывая ваши комментарии, вы, кажется, путаете 64-битные и 32-битные.

x86 означает 32-разрядный, а amd64 означает 64-разрядный.

  • x86 32-битный компилятор, который выдает 32-битный exe
  • x86_amd64 32-битный компилятор, который выдает 64-битный exe
  • amd64 64-битный компилятор, который выдает 64-битный exe
  • amd_x86 64-битный компилятор, который выдает 32-битный exe

Поэтому, если вы хотите создавать 32-битные программы, вы можете использовать x86 или amd64_x86 . Если вы хотите создавать 64-битные программы, вы можете использовать amd64 или x86_amd64 .

Если в какой-то момент вы захотите скомпилировать Qt porgam, но Qt Creator не распознает ваш набор инструментов MSVC, у вас все еще есть решение:

  1. Откройте Qt 5.12.4 (MSVC 2017 64-bit) из меню Пуск
  2. В командной строке выполните C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat amd64
  3. Беги qmake и наслаждайся

Вы не можете вручную добавить MSVC в Qt Creator. Если вы хотите использовать его, убедитесь, что установлена правильная версия Visual Studio.

Я предлагаю переустановить Visual Studio, если компилятор MSVC не отображается на вкладке «Компиляторы».

Tutorial: Configure CLion on Windows

On Windows, CLion toolchains include the build tool, C and C++ compilers, debugger executable, and the environment. You can select one of the pre-defined toolchain setups (MinGW, Cygwin, Microsoft Visual C++, or WSL), Remote Host, Docker) or configure a custom toolchain (System):

Windows toolchain options

Watch this video for an overview of Windows toolchain options:

If you don’t need to configure custom tools or don’t want to install additional software on your system, stick to MinGW (default) as it works out-of-the-box using the MinGW toolset bundled in CLion.

For details on Remote Host toolchains, see Remote with local sources. If you are working with a Docker container, see Docker toolchain.


CLion bundles a version of the MinGW toolset for quick setup. The exact version bundled is MinGW-w64 9.0 with languages=c,c++ , posix threads, and seh exceptions. You can use this bundled toolchain or switch to a custom MinGW installation.

Install MinGW (optional)

Download and run the MinGW-w64 installer. It provides both 64- and 32-bit options.

In the MinGW-w64 installation wizard, make sure to select the required architecture. Note that the default suggested option is 32-bit.

Wait for installation to finish.

Although MinGW-w64 provides both 64- and 32-bit options, you can also install MinGW, the 32-bit-only version.

In the MinGW installation wizard, select the following packages from the Basic Setup list: mingw-developer-tool , mingw32-base , mingw32-gcc-g++ , mingw32-msys-base .

Wait for installation to finish.

Configure a MinGW toolchain

Go to File | Settings | Build, Execution, Deployment | Toolchains .

Click and select MinGW to add a new MinGW toolchain.

In the Toolset field, you will see Bundled MinGW , which is the default option. If required, open the field to select from the list of other available installations:

Bundled MinGW toolchain

Wait until the tools detection finishes.

Select the Debugger : you can use either bundled GDB, your MinGW GDB, or a custom GDB binary.

The recommended option is bundled GDB, since it is guaranteed to include Python support required for CLion data renderers.

Click Apply when all the tools are set correctly.

When using a custom MinGW installation, if CLion cannot detect the compilers, double-check the installed packages in MinGW Installation Manager .


Download the Cygwin installer, version 2.8 or later.

Cygwin installation

To select a package, type its name in the Search field and set the version in the New column:

Once the installation is finished, open CLion and go to File | Settings | Build, Execution, Deployment | Toolchains .

Click and select Cygwin to add a new Cygwin toolchain.

CLion will attempt to detect the Cygwin installation automatically. Check the Toolset field, and specify the path manually if required.

Cygwin toolchain

Wait until the tools detection finishes, and click Apply .

Windows Subsystem for Linux

You can use WSL, Windows Subsystem for Linux, as your working environment in CLion on Windows 10 (starting the Fall Creators Update version 1709, build 16299.15).

WSL toolchain enables you to build projects using CMake and compilers from Linux and run/debug on WSL without leavCLionLion running on your Windows machine.

Refer to our WSL guide for details on setting up WSL on your system and configuring WSL toolchainsCLionLion.

WSL toolchain

Microsoft Visual C++

Install Visual Studio 2013, 2015, 2017, 2019, or 2022 on your system.

In CLion, go to File | Settings | Build, Execution, Deployment | Toolchains .

Click and select Visual Studio from the list of toolchain templates.

Check the Toolset field. CLion will attempt to automatically detect the installed Visual Studio distribution. If the detection fails, set the path to Visual Studio manually.

If required, specify the Architecture ( x86 , amd64 , x86_arm , or another), Platform ( store , uwp , onecore , or leave it blank), and Version . To build your project for the selected architecture, CLion will call the script to configure the environment with the specified parameters.

If the version of your compiler toolset is earlier than the version of your Visual Studio installation, pass it in the Version field via the vcvars_ver flag, for example, -vcvars_ver=14.16 .

Wait until the tools detection is finished:

MSVC compiler

CLion supports the Microsoft Visual C++ compiler that ships with Visual Studio 2013, 2015, 2017, 2019, and 2022.

__uuidof , __forceinline , __unaligned , and __alignof keywords;

pointer type attributes: __ptr32 , __ptr64 , __uptr , __sptr ;

MSVC built-in data types: (unsigned) __int8 , (unsigned) __int16 , (unsigned) __int32 , (unsigned) __int64 , __wchar_t ;

additional format specifiers, such as %I32 and %I64 ;

the clang’s -fms-extensions flag.

Clang-cl compiler

As an alternative compiler, you can use clang-cl — the MSVC-compatible compiler driver for Clang. CLion supports clang-cl version 8.0 and later.

Install clang-cl from the LLVM site or along with the Visual Studio tools.

When installed from the LLVM site, the clang-cl binary can be found at the standard location C:\Program Files\LLVM\bin\clang-cl.exe for the 64-bit version or C:\Program Files (x86)\LLVM\bin\clang-cl.exe for the 32-bit version.

In CLion, go to File | Settings | Build, Execution, Deployment | Toolchains and select the Visual Studio toolchain that you want to configure, or create a new one.

Clang-cl compiler

Point the C Compiler and C++ Compiler fields to clang-cl.exe . CLion will suggest the paths detected automatically.

Note that currently the -T clangcl options can’t be picked up if the bundled CMake is in use along with the Visual Studio toolchain setup (CPP-18848).

MSVC debugger

The MSVC toolchain debugger is implemented on top of LLDB, and it can work with native visualizers from the Visual Studio installation or from your project.


To enable native visualizers support and set the desired diagnostics level, select the Enable NatVis renderers for LLDB checkbox in Settings | Build, Execution, Deployment | Debugger | Data Views | C/C++ :

CLion automatically generates one-line summaries for all structures not covered by Natvis and highlights them to increase readability. Also, the built-in formatters provide visualization for wide/Unicode strings ( wchar_t , char16_t , char32_t ).

MSVC debug with custom NatVis

If you have custom native visualizers in your project, CLion will use them as well.

When using the MSVC toolchain debugger, you can enable symbol servers support which will help the debugger resolve library symbols correctly. For more details, refer to Using symbol servers when debugging on Windows.

System toolchain

The System toolchain on Windows allows configuring the build tool, compilers, and debugger without selecting a predefined toolset or environment, similarly to Linux and macOS. Use this toolchain option for embedded development cases like using ARM or for other custom setups.

Go to File | Settings | Build, Execution, Deployment | Toolchains .

Click and select System to add a new System toolchain.

Configure the tools and provide an environment script if required:

Initializing the toolchain environment via a script

Instead of setting the environment manually, you can point CLion to an environment file — a script that initializes the environment for your project. This is helpful, for example, when you need to initialize compiler variables, add custom ones, or modify the PATH .

Specifying an environment script is available for all toolchains.

Environment sourcing will happen on the first actual usage of the toolchain in a CMake profile or upon loading a Makefile project.

In the toolchain settings, click Add environment , then click From file :

In the Environment file field, specify the path to the script:

You will get notifications in case of script loading issues. CLion also checks the script loading time and terminates the execution if it takes too long.

Clang compiler on Windows

With CMake 3.15, it has become possible to use the Clang compiler on Windows with the MinGW-w64/MinGW toolchain.

However, the 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 if you take Clang from the LLVM repository, it will not work correctly when configured with the MinGW toolchain. One of the possible workarounds is described below.

Set up the Clang compiler for MinGW

Download the following packages with the pacman tool (use the pacman -S package_name command):

This way, you will get the Clang compiler which is built with mingw-w64 and has paths and macros that correspond to this toolchain.

Go to Settings | Build, Execution, Deployment | Toolchains , create a MinGW toolchain, and set up the tools from MSYS.

After specifying the Toolset , check the automatically detected tools and make sure to switch to Clang in the C Compiler and C++ Compiler fields.

With this new toolchain configured, you can build the project and start using the Clang’s advances tools, such as profile-guided optimization. Take a look at our detailed blogpost for instructions.

GDB on Windows

In the case of MinGW, CLion includes the bundled GDB (version 12.1). For Cygwin, you need to install the GDB package in the Cygwin Package Manager, as described in the Cygwin section of this guide.

You can also switch to a custom GDB binary. In this case, the supported GDB versions are 7.8.x-12.1.

Install (MSVC)

Here we describe how to compile OpenBabel on Windows using the Microsoft Visual C++ compiler (MSVC).


Compiling the 2.2.x series


We recommend the following compiler which is available for free:

Microsoft would prefer you use the .NET framework, but they also support «native» code — it’s just that they don’t make it too easy.

You also need to install the Platform SDK to provide the Windows files. Follow the step 1 to 3 in the instructions in [1]. At Step 3 when updating the corewin_express.vsprops file, the list of libraries should be «kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comctl32.lib rpcrt4.lib». Also just before this add a section:

This (usually) avoids warnings about unsafe functions like sprintf for which Microsoft have provided «safe» alternatives. Read a critique of these here. They are not usable in cross-platform code because they are non-standard. Ignore any such warnings that have failed to be supressed.

OpenBabel source code

Although the source code package from the SourceForge download page has all the OpenBabel code, it may not have some of the ancillary files, since it is really intended for UNIX(Linux) systems. If you intend to compile under Windows it is much better to download the code from SVN. Tortoise SVN is a very convenient client for SVN — it operates from Windows explorer — and is easy to install. Then make a directory for the OpenBabel file, right click and select SVN Checkout. For a released version of OpenBabel enter something like:

or for the development code:

Click OK and all the code and required external DLLs (e.g. for InChI and libxml2) are downloaded.


You need to install some elements of the Boost Library. This is done as follows:

  • Download and run the BoostPro 1.34.1 Installer
  • Choose the Visual Studio 2005 version
  • Choose both of the single thread variants
  • On the next screen, choose just the Boost header files and deselect everything else
  • Complete the installation
  • Open windows-vc2005/OpenBabelOBF.sln with Visual Studio and from the Menu choose Project, Properties, C/C++, Additional Include Directories and add C:\Program Files\boost\boost_1_34_1 (or whereever you installed Boost)
Environment Variable

Make an environment variable BABEL_DATADIR to point to OpenBabel’s /data folder. This needed for functions like logP, although the basic data, like atomic weights, are also compiled into the program and will be found even if this variable is not set.

Basic build

At this stage you should be able to compile the command-line version of OpenBabel. Open windows-vc2005/OpenBabelOBF.sln and build all the projects except OBPythonOBF, OBJava, OBCSharp and OBGUI. In this build, the core is contained in multiple DLLs, and formats and extensions as plugin *.obf files. This allows the package to be expanded or slimmed after compilation by adding or removing obf files. In the Release build these files are in the window-vc2005 folder and in the Debug build in windows-vc2005/debug.

Compiling your own programs

There is an example program in window-vc2005/examples which is usable as a template for application programs. It has a Debug build which eases the development of such programs and can also assist in understanding the workings of API calls. It expects the main OpenBabel lib files to be where they were built during the main build. If you want to build your program elsewhere you will need to adjust the Additional Library Directories in the Linker section of the project properties.

window-vc2005/Tools.sln has projects for several small programs based on the OpenBabel API to do useful things, and may also be a model for further applications. There is a brief description of these in window-vc2005/OBTools/Projects in OBTools.txt and Guides and Tutorial:Other_Tools.

Compiling wxWidgets

To compile the Windows GUI, you will need to install and compile wxWidgets. We are currently using wxWidgets 2.8.3. To compile it.

  • Unzip it into a folder that doesn’t contain spaces
  • Read the install notes in the distribution
  • Read more install notes on the web site
  • Set the environment variable WXWIN to the installation directory of wxWidgets, e.g. E:\wxWidgets-2.8.3, and restart MSVC.
  • In the file$(WXWIN)/include/wx/msw/setup.h change
  • In the file $(WXWIN)/include/wx/msw/wx.rc find the section «Manifest file for Windows XP» and add immediately after it:

This ensures that the latest version of Common Controls is used.

  • Open «build\msw\wx.dsw» and answer «Yes to All» for the format conversion. (There is no need to save the converted project files.)
  • On the menu, choose «Batch Build», and sort by «Configuration». Select only those configurations of type «Release» and, possibly «Debug», and click on Build All.

The GUI can be built by opening OpenBabelOBF.sln and building the project OBGUI.

Debugging with Visual Studio

If you do a significant amount of debugging of OpenBabel code, you may wish to have the OpenBabel objects appear in the the Autos or Locals debugging windows in a more useful form. There is a lot that can be done but the simple suggestion here is a start.

Edit the file C:\Program Files\Microsoft Visual Studio 8\Common7\Packages\Debugger\autoexp.dat
In the [AutoExpand] section add the following text

and restart Visual Studio.
In the debugger OBMol, OBAtom and wxString objects will be easier to identify.

Scripting Interfaces

As downloaded from SVN, the solution has the projects for the scripting interfaces, OBPythonOBF, OBJava and OBCSharp, disabled so that they are not built by Build Solution. To build them you need to first install SWIG. Use the latest release of SWIG.

OBJava and OBCSharp built in the release configuration. The OBPythonOBF project has several configurations corresponding to different versions of Python (the default Release configuration will fail with an error).

To configure for version(s) of Python on your computer:

  • Edit windows-vc2005/setenv.txt so that the environment variable(s) correspond to your system. The irrelevant environment variables can be ignored.
  • Save as windows-vc2005/setenv.bat
  • Double click on setenv.bat to start MSVC++ with the variables set.
  • Set the Solution Configuration to Release (on the toolbar).
  • In the Configuration Manager (on the Build menu) set the Configuration of the OBPythonOBF project to the version you wish to build.

Build OBPythonOBF, OBJava or OBCSharp. If necessary, OBPython can be rebuilt with additional configurations.

Building the Windows Installer

The Windows installer uses a script compiled by NSIS. All the above projects, including the GUI and scripting, need to have been built. Download the Visual C++ Redistributable and put the file vcredist_x86.exe into windows-vc2005/Distribution. Right click the script file in that folder to compile it.

Compiling the 2.3.x series (subversion trunk)

Compiler and Build System

We recommend the following compiler which is available for free:

You also need to install CMake 2.6.x. Install into the default location.

Compiling wxWidgets

If you are not interested in compiling the OpenBabel GUI, you can skip this section.

To compile the Windows GUI, you will need to install and compile wxWidgets. We are currently using wxWidgets 2.8.3. To compile it.

  • Unzip it into a folder that doesn’t contain spaces
  • Read the install notes in the distribution
  • Read more install notes on the web site
  • Set the environment variable WXWIN to the installation directory of wxWidgets, e.g. E:\wxWidgets-2.8.3, and restart MSVC.
  • In the file$(WXWIN)/include/wx/msw/setup.h change
  • In the file $(WXWIN)/include/wx/msw/wx.rc find the section «Manifest file for Windows XP» and add immediately after it:

This ensures that the latest version of Common Controls is used.

  • Open «build\msw\wx.dsw» and answer «Yes to All» for the format conversion. (There is no need to save the converted project files.)
  • On the menu, choose «Batch Build», and sort by «Configuration». Select only those configurations of type «Release» and, possibly «Debug», and click on Build All.
Get the OpenBabel source code

The OpenBabel source code should be checked out of the Subversion (SVN) repository. Install Tortoise SVN. Then make a directory for the OpenBabel files, right click on it and select SVN Checkout. Enter

Установка поддержки C++ в Visual Studio Code (VSCode)

Для разработки программ на языке c++ вы можете использовать среду разработки Visual Studio Code (VSCode).

Сегодня мы рассмотрим установку поддержки языка программирования с++ в этой IDE.

Выбор компилятора

Перед установкой расширения для поддержки с++ в VSCode нам нужно сначала определиться какой компилятор использовать.

Под Windows существует несколько возможностей:

  • Вы можете использовать Windows Subsystem for Linux (WSL) и установив в виртуальной машине все необходимые пакеты компилировать программы с помощью специального расширения для VSCode.
  • Вы можете установить MinGW или MSYS2 и использовать их компиляторы.
  • Вы можете установить компилятор Microsoft C++ compiler (MSVC)

Сегодня мы рассмотрим самый простой способ – установку Microsoft C++ compiler (MSVC).

Установка Microsoft C++ compiler (MSVC)

Для начала скачаем установщик по ссылке:

Скачиваем файл, в моем случае он называется:

Запускаем, откроется окно:


Нажимаем «Продолжить» и ждем, пока не закончиться скачивание файлов:


После этого откроется окно:


Поставьте галочку рядом с Разработка классических приложений на C++


К сожалению, нет способа не ставить саму IDE.

Снимите галочки с:

  • Live Share
  • С++ AddressSanitizer
  • Адаптер тестов для Boost.Test
  • Адаптер тестов для Google Test


Ожидайте окончания установки.

После окончания загрузок перезагрузите ваш ПК

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

После перезагрузки проверим доступен ли компилятор, для этого запустите cmd.exe скопируйте и вставьте в консоль строку

Будет запущена консоль разработчика:

Компилятор успешно установлен и доступен.

Теперь пришло время установить расширение для поддержки с++ в VSCode.

Установка расширения для поддержки С++ в VSCode

Откроется панель Extensions: Marketplace – это каталог, из которого мы можем скачать все необходимые расширения и темы, достаточно знать их название.



Выберите указанный пункт и нажмите install


Будет начато скачивание дополнительных компонентов. После окончания загрузок расширение будет готово к использованию.

Настройка VSCode для использования компилятора MSVC

Для того, чтобы протестировать работу компилятора создадим тестовый проект.

Для нормального функционирования компилятора MSVC нужно установить несколько переменных окружения. Чтобы упростить задачу воспользуемся Visual Studio 2019 Developer Command Prompt.

Запустите его из меню Пуск введя слово developer, откроется консоль:


Допустим, наши проекты буду находится в папке d:\cpp

Создадим данную папку и перейдем в нее:

Создадим папку для проекта test

Запустим VSCode из этой папки

Откроется окно VSCode


Обратите внимание наша папка уже открыта.

Добавим новый файл для этого нажмите на кнопку:


В появившееся поле введите имя файла main.cpp

Введите текст программы и не забудьте сохранить результат:

Настройка компилятора для проекта

Теперь у нас есть программа, осталось её скомпилировать, давайте настроим задачу сборки для проекта.

Настройка задачи сборки (Build Task)

Выберите пункт меню Terminal –> Configure Default Build Task…


В окне выберите – cl.exe

Будет создан файл сборки:


Закройте вкладку с файлом tasks.json

Откройте файл main.cpp и нажмите


Сборка успешно завершена.

Щёлкните мышкой по терминалу и нажмите пробел, чтобы закрыть результаты сборки.

Введите main.exe и нажмите Enter


Поздравляю, мы успешно настроили среду разработки VSCode для работы с языком программирования C++.


Сегодня мы добавили поддержку языка программирования C++ в среду разработки VSCode.

Нами был установлен компилятор Microsoft C++ compiler (MSVC) и проверена его работоспособность.

Мы добавили тестовый проект и настроили задачу сборки Build Task для нашего проекта.

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

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