Выбор компилятора visual studio
Microsoft Visual Studio 2017 supports several C++ compilers to suit a wide variety of codebases. In addition to the Microsoft Visual C++ compiler that many of you are likely familiar with, Visual Studio 2017 also supports Clang, GCC, and other compilers when targeting certain platforms.
This post is intended to familiarize you with the variety of C++ compilers that are compatible with the Visual Studio IDE, and to understand when they might be applicable to use with your projects. Some compilers may be better suited to your needs depending on your project or target. Alternatively, you may be interested in checking out new language features, such as C++ Concepts, that are not available across all compilers without needing to leave the IDE.
You can select the compiler and corresponding toolset that will be used to build a project with the “Platform Toolset” property under General Configuration Properties for C++ projects. Any installed compilers that are applicable to your project type will be listed in the “Platform Toolset” dropdown.
Microsoft C++ Compiler (MSVC)
If you are targeting Windows, the Microsoft C++ compiler (MSVC) may be the way to go. This is the default compiler for most Visual Studio C++ projects and is recommended if you are targeting Windows.
Compiler options for the Microsoft C++ compiler.
Clang
You can use the Clang compiler with Visual Studio to target Android, iOS, and Windows.
If you are targeting Android, you can use the Clang/LLVM compiler that ships with the Android NDK and toolchain to build your project. Likewise, Visual Studio can use Clang running on a Mac to build projects targeting iOS. Support for Android and iOS is included in the “Mobile Development with C++” workload. For more information about targeting Android or iOS check out our posts tagged with the keywords “Android” and “iOS”.
If you are targeting Windows, you have a few options:
- Use Clang/LLVM; “Clang for Windows” includes instructions to install Clang/LLVM as a platform toolset in Visual Studio.
- Use Clang to target Windows with Clang/C2 (Clang frontend with Microsoft Code Generation).
Compiler options for the Clang/C2 compiler.
It might make sense to use Clang/C2 if you want to bring a codebase that takes advantage of Clang’s language features to the Windows platform. Since the code generation and optimization is handled by the MSVC backend, binaries produced by Clang/C2 are fully compatible with binaries produced by MSVC. You can learn more about Clang/C2 from Clang with Microsoft Codegen – or check out the latest updates in posts tagged with the keyword “clang”.
If your project targets Linux or Android, you can consider using GCC. Visual Studio’s C++ Android development natively supports building your projects with the GCC that ships with the Android NDK, just like it does for Clang. You can also target Linux – either remotely or locally with the Windows Subsystem for Linux – with GCC.
Compiler options for GCC.
Check out our post on Visual C++ for Linux Development for much more info about how to use Visual Studio to target Linux with GCC. If you are specifically interested in targeting WSL locally, check out Targeting WSL from Visual Studio.
Closing
Visual Studio also makes use of the Edison Design Group (EDG) frontend to provide flexible IntelliSense regardless of whether you use MSVC, Clang, or GCC to build your code. Visual Studio gives you access to a wide range of choices when it comes to C++ compilers. This way you can make sure that as you develop your code, it continues to compile against all major compilers.
Install Visual Studio today and give it a try. Please let us know if we have missed any compilers you use, and share your feedback as we look forward to improving your C++ development experience.
Набор инструментов платформы
Набор инструментов платформы состоит из компилятора C++ (cl.exe) и компоновщика (link.exe) вместе со стандартными библиотеками C/C++. Studio 2015, Visual Studio 2017 и Visual Studio 2019 совместимы на уровне двоичного кода. Об этом свидетельствует основной номер версии набора инструментов, который остался равным 14. Проекты, скомпилированные в Visual Studio 2019 или Visual Studio 2017 обратно совместимы на уровне ABI с проектами, скомпилированными в Visual Studio 2017 или Visual Studio 2015. Дополнительный номер версии обновляется на 1 для каждой версии с выпуска Visual Studio 2015:
- Visual Studio 2015: v140
- Visual Studio 2017: v141
- Visual Studio 2019: v142
- Visual Studio 2022: v143
Целевая платформа (только для проектов C++/CLI)
Создавая пользовательские наборы инструментов платформы, можно расширить поддержку целевой платформы. Дополнительные сведения см. в блоге по Visual C++ Нативное многоплатформенное нацеливание в C++ .
В обозревателе решенийVisual Studio выберите проект. В строке меню откройте меню Проект и выберите Выгрузить проект. Это выгружает файл проекта (VCXPROJ) для вашего проекта.
Проект на языке C++ не может быть загружен, пока вы редактируете файл проекта в Visual Studio. Однако можно использовать другой редактор, например блокнот, чтобы изменить файл проекта, пока проект загружен в Visual Studio. Visual Studio определяет, что файл проекта был изменен и отображает запрос о необходимости перезагрузить проект.
В строке меню последовательно выберите Файл, Открыть, Файл. В диалоговом окне Открыть файл перейдите к папке проекта и откройте файл проекта (с расширением VCXPROJ).
Сохраните изменения и закройте редактор.
В разделе Обозреватель решенийоткройте контекстное меню своего проекта и выберите Перезагрузить проект.
Изменение набора инструментов платформы
В диалоговом окне выберите страницу свойств Свойства конфигурации>Общие.
На странице свойств щелкните Набор инструментов платформы и выберите необходимый набор инструментов из раскрывающегося списка. Например, если вы установили набор инструментов Visual Studio 2010, выберите Visual Studio 2010 (версия 100) для использования в проекте.
В интегрированной среде разработки все сведения, необходимые для построения проекта, предоставляются в виде свойств. Эти сведения включают в себя имя приложения, расширение (например, DLL, EXE, LIB), параметры компилятора, параметры компоновщика, параметры отладчика, настраиваемые этапы сборки и многие другие компоненты. Как правило, для просмотра и изменения этих свойств используются страницы свойств. для доступа к страницам свойств выберите Project свойствапроекта в главном меню или щелкните правой кнопкой мыши узел проекта в обозреватель решений и выберите пункт свойства.
Свойства по умолчанию
При создании проекта система задает значения для различных свойств. Значения по умолчанию варьируются в зависимости от типа проекта и параметров, выбранных в мастере приложений. Например, проект ATL имеет свойства, связанные с MIDL-файлами, но эти свойства отсутствуют в базовом консольном приложении. В области "Общие" на страницах свойств отображаются свойства по умолчанию:
Применение свойств к конфигурациям сборок и целевым платформам
Некоторые свойства, такие как имя приложения, применяются ко всем вариантам сборки и целевым платформам, будь это сборка отладки или выпуска. Однако большинство свойств зависит от конфигурации. Чтобы создать правильный код, компилятор должен иметь как конкретную платформу, в которой будет выполняться программа, так и конкретные параметры компилятора. Поэтому при задании свойства важно обратить внимание на ту конфигурацию и платформу, к которым должно применяться новое значение. Должен ли он применяться только для отладки сборок Win32 или должен также применяться к отладке ARM64 и отладке x64? Например, для свойства оптимизации по умолчанию задано значение максимизировать скорость (/O2) в конфигурации выпуска, но оно отключено в конфигурации отладки.
Вы всегда можете видеть и изменять конфигурацию и платформу, к которым должно применяться значение свойства. На следующем рисунке показаны страницы свойств с элементами управления конфигурацией и сведениями о платформе в верхней части. Если свойство оптимизации задано здесь, оно будет применяться только для отладки сборок Win32, текущей активной конфигурации, как показано красными стрелками.
На следующем рисунке показана та же страница свойств проекта, но конфигурация изменена на выпуск. Обратите внимание на другое значение для свойства "Оптимизация". Кроме того, обратите внимание, что активной конфигурацией по-прежнему является отладка. Здесь вы можете задать свойства для любой конфигурации, а не только активной.
Целевые платформы
Целевая платформа относится к типу устройства и операционной системы, на которых будет выполняться исполняемый файл. Вы можете создать проект для нескольких платформ. Доступные целевые платформы для проектов C++ зависят от типа проекта. В их число входят только Win32, x64, ARM, ARM64, Android и iOS. Целевая платформа X86, которую вы могли заметить в Configuration Manager, идентична Win32 в собственных проектах C++. Win32 означает 32-разрядную версию Windows, а x64 — 64-разрядную. Дополнительные сведения об этих двух платформах см. в разделе Запуск 32-разрядных приложений.
Дополнительные сведения настройке свойств отладочной сборки см. в следующих разделах:
Параметры компилятора и компоновщика C++
Параметры компилятора и компоновщика C++ находятся в узлах C/C++ и Компоновщик на панели слева в разделе Свойства конфигурации. Эти параметры непосредственно преобразуются в параметры командной строки, которые будут переданы компилятору. Чтобы ознакомиться с документацией по конкретному параметру, выберите параметр в центральной области и нажмите клавишу F1. также можно просмотреть документацию по всем параметрам в MSVC параметры компилятора и параметры компоновщика MSVC.
Значения каталога и пути
MSBuild поддерживает использование констант времени компиляции для определенных строковых значений, таких как включаемые каталоги и пути, называемые макросами. макрос может ссылаться на значение, определенное Visual Studio или системой MSBuild, или на значение, определенное пользователем. Макросы выглядят как $(macro-name) или %(item-macro-name) . Они представлены на страницах свойств, на которых можно ссылаться и изменять их с помощью редактора свойств. Вместо жестко запрограммированных значений, таких как пути к каталогам, используйте макросы. Макросы упрощают совместное использование параметров свойств между компьютерами и версиями Visual Studio. Кроме того, можно обеспечить правильное участие в параметрах проекта в наследовании свойств.
На следующем рисунке показаны страницы свойств для проекта Visual Studio C++. в левой области выбрано правило VC++ каталоги , а на правой панели перечислены свойства, связанные с этим правилом. Значения свойств часто являются макросами, например $(VC_SourcePath) :
Для просмотра значений всех доступных макросов можно использовать Редактор свойств .
Предустановленные макросы
Глобальные макросы:
Глобальные макросы применяются ко всем элементам в конфигурации проекта. Глобальный макрос имеет синтаксис $(name) . Пример глобального макроса — свойство $(VCInstallDir) , которое сохраняет корневой каталог установки Visual Studio. Глобальный макрос соответствует элементу PropertyGroup в MSBuild.
Макросы элементов
Макросы элементов имеют синтаксис %(name) . Для файла макрос элемента применяется только к этому файлу, — например, можно использовать, %(AdditionalIncludeDirectories) чтобы указать каталоги включаемых файлов, которые применяются только к конкретному файлу. Этот тип макроса элемента соответствует метаданным ItemGroup в MSBuild. При использовании в контексте конфигурации проекта макрос элемента применяется ко всем файлам определенного типа. Например, свойство конфигурации определений препроцессора C/C++ может принимать макрос элемента, который применяется ко всем cpp-файлам в проекте. Этот тип макроса элемента соответствует метаданным ItemDefinitionGroup в MSBuild. Дополнительные сведения см. в разделе Определения элементов.
Пользовательские макросы
Вы можете создавать пользовательские макросы для использования в качестве переменных в сборках проекта. Например, можно создать пользовательский макрос, предоставляющий значение пользовательскому шагу сборки или пользовательскому средству сборки. Пользовательский макрос — это пара "имя-значение". Для доступа к этому значению в файле проекта используется нотация $(name) .
Пользовательский макрос хранится на странице свойств. если проект еще не содержит страницу свойств, его можно создать, выполнив действия, описанные в разделе общий доступ или повторное использование Visual Studio параметры проекта.
Создание пользовательского макроса
В левой области диалогового окна выберите Пользовательские макросы. В правой области нажмите кнопку Добавить макрос, чтобы открыть диалоговое окно Добавление пользовательского макроса.
В диалоговом окне задайте имя и значение для макроса. Кроме того, можно установить флажок Задание данного макроса в качестве переменной среды в среде сборки.
Редактор свойств
Редактор свойств можно использовать для изменения некоторых строковых свойств и выбора макросов в качестве значений. Чтобы открыть редактор свойств, выберите свойство на странице свойств, а затем нажмите кнопку со стрелкой вниз справа. Если раскрывающийся список содержит Правка >, можно выбрать его, чтобы отобразить редактор свойств для этого свойства.
В редакторе свойств можно нажать кнопку Макросы, чтобы просмотреть доступные макросы и их текущие значения. На следующем рисунке показан редактор свойств для свойства Дополнительные каталоги включаемых файлов после нажатия кнопки Макросы. Если установлен флажок наследовать от родительского объекта или проекта по умолчанию и добавить новое значение, то оно добавляется к любому значению, наследуемому в данный момент. Если снять флажок, новое значение заменяет наследуемые значения. В большинстве случаев следует не снимать этот флажок.
Добавление каталога включения к набору каталогов по умолчанию
При добавлении каталога включения в проект важно не переопределять все каталоги по умолчанию. Правильный способ добавления каталога — добавить новый путь, например " C:\MyNewIncludeDir\ ", а затем добавить $(IncludePath) макрос к значению свойства.
Быстрый просмотр и поиск всех свойств
Без префикса:
поиск только в именах свойств (подстрока без учета регистра).
" / " или " - ":
поиск только в параметрах компилятора (префикс без учета регистра)
v :
поиск только в значениях (подстрока без учета регистра).
Задание переменных среды для сборки
компилятор MSVC (cl.exe) распознает определенные переменные среды, в частности LIB ,, LIBPATH PATH и INCLUDE . при построении с помощью интегрированной среды разработки свойства, заданные на странице свойств каталоги VC++ , используются для задания этих переменных среды. если LIB LIBPATH значения, и INCLUDE уже заданы, например Командная строка разработчика, они заменяются значениями соответствующих свойств MSBuild. затем сборка добавляет значение свойства VC++ каталоги исполняемых каталогов в PATH . Для задания пользовательской переменной среды можно создать пользовательский макрос и затем установить флажок Задание данного макроса в качестве переменной среды в среде сборки.
Задание переменных среды для сеанса отладки
В правой области измените параметры проекта Среда или Объединение среды, а затем нажмите кнопку ОК.
Содержание раздела
Совместное или повторное использование параметров проекта Visual Studio
Создание .props файла с настраиваемыми параметрами сборки, которые можно использовать совместно или повторно.
Наследование свойств проекта
Описывает порядок вычисления для .props .targets .vcxproj переменных среды,, файлов и в процессе сборки.
Изменение свойств и целевых объектов без изменения файла проекта
Создание временных параметров сборки без изменения файла проекта.
In this tutorial, you configure Visual Studio Code to use the GCC C++ compiler (g++) and GDB debugger from mingw-w64 to create programs that run 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 about GCC, GDB, Mingw-w64, 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.
Prerequisites
To successfully complete this tutorial, you must do the following steps:
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 ) ).
Get the latest version of Mingw-w64 via MSYS2, which provides up-to-date native builds of GCC, Mingw-w64, and other helpful C++ tools and libraries. You can download the latest installer from the MSYS2 page or use this link to the installer.
Follow the Installation instructions on the MSYS2 website to install Mingw-w64. Take care to run each required Start menu and pacman command, especially Step 7, when you will install the actual Mingw-w64 toolset ( pacman -S --needed base-devel mingw-w64-x86_64-toolchain ).
Add the path to your Mingw-w64 bin folder to the Windows PATH environment variable by using the following steps:
- In the Windows search bar, type 'settings' to open your Windows Settings.
- Search for Edit environment variables for your account.
- Choose the Path variable in your User variables and then select Edit.
- Select New and add the Mingw-w64 destination folder path to the system path. The exact path depends on which version of Mingw-w64 you have installed and where you installed it. If you used the settings above to install Mingw-w64, then add this to the path: C:\msys64\mingw64\bin .
- Select OK to save the updated PATH. You will need to reopen any console windows for the new PATH location to be available.
Check your MinGW installation
To check that your Mingw-w64 tools are correctly installed and available, open a new Command Prompt and type:
If you don't see the expected output or g++ or gdb is not a recognized command, make sure your PATH entry matches the Mingw-w64 binary location where the compilers are located. If the compilers do not exist at that PATH entry, make sure you followed the instructions on the MSYS2 website to install Mingw-w64.
Create Hello World
From a Windows command prompt, create an empty folder called projects where you can place all your VS Code projects. Then create a sub-folder called helloworld , navigate into it, and open VS Code in that folder by entering the following commands:
The "code ." command opens VS Code in the current working folder, which becomes your "workspace". Accept the Workspace Trust dialog by selecting Yes, I trust the authors since this is a folder you created.
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:
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:
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.
Build helloworld.cpp
Next, you'll create a tasks.json file to tell VS Code how to build (compile) the program. This task will invoke the g++ compiler to create an executable file based on the source code.
From the main menu, choose Terminal > Configure Default Build Task. In the dropdown, which will display a tasks dropdown listing various predefined build tasks for C++ compilers. Choose g++.exe build active file, which will build the file that is currently displayed (active) in the editor.
This will create a tasks.json file in a .vscode folder and open it in the editor.
Your new tasks.json file should look similar to the JSON below:
The command setting specifies the program to run; in this case that is g++. The args array specifies the command-line arguments that will be passed to g++. These arguments must be specified in the order expected by the compiler. This task tells g++ to take the active file ( $ ), compile it, and create an executable file 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.
Note: You can learn more about tasks.json variables in the variables reference.
The label value is what you will see in the tasks list; you can name this whatever you like.
The "isDefault": true value in the group object specifies that this task will be run when you press ⇧⌘B (Windows, Linux Ctrl+Shift+B ) . This property is for convenience only; if you set it to false, you can still run it from the Terminal menu with Tasks: Run Build Task.
Running the build
Go back to helloworld.cpp . Your task builds the active file and you want to build helloworld.cpp .
To run the build task defined in tasks.json , press ⇧⌘B (Windows, Linux Ctrl+Shift+B ) or from the Terminal main menu choose Run Build Task.
When the task starts, you should see the Integrated Terminal panel appear below the source code editor. After the task completes, the terminal shows output from the compiler that indicates whether the build succeeded or failed. For a successful g++ build, the output looks something like this:
Create a new terminal using the + button and you'll have a new terminal with the helloworld folder as the working directory. Run dir and you should now see the executable helloworld.exe .
You can run helloworld in the terminal by typing helloworld.exe (or .\helloworld.exe if you use a PowerShell terminal).
Note: You might need to press Enter a couple of times initially to see the PowerShell prompt in the terminal. This issue should be fixed in a future release of Windows.
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
Next, you'll create a launch.json file to configure VS Code to launch the GDB debugger when you press F5 to debug the program.
- From the main menu, choose Run >Add Configuration. . VS Code creates an empty launch.json file.
- Copy and paste the following configuration into launch.json :
The program setting 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 .
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.
Note: The preLaunchTask setting is used to specify task to be executed before launch. Make sure it is consistent with the tasks.json file label setting.
Start a debugging session
- Go back to helloworld.cpp so that it is the active file.
- Press F5 or from the main menu choose Run > Start Debugging. Before you start stepping through the source 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 first statement in the main method. This is a breakpoint that the C++ extension automatically sets for you:
The Run 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.
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.
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!
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.
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.
When the loop has completed, you can see the output in the Integrated Terminal, along with some other diagnostic information that is output by GDB.
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, click 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.
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.
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 ) ).
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.
Here, we've changed the Configuration name to GCC, set the Compiler path dropdown to the g++ compiler, and the IntelliSense mode to match the compiler (gcc-x64)
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 extension uses the compilerPath setting to infer the path to the C++ standard library header files. When the extension knows where to find those files, it can provide 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++ compiler
- Then look for g++ on Windows Subsystem for Linux (WSL)
- Then g++ for Mingw-w64.
If you have Visual Studio or WSL installed, you may need to change compilerPath to match the preferred compiler for your project. For example, if you installed Mingw-w64 version 8.1.0 using the i686 architecture, Win32 threading, and sjlj exception handling install options, the path would look like this: C:\Program Files (x86)\mingw-w64\i686-8.1.0-win32-sjlj-rt_v6-rev0\mingw64\bin\g++.exe .
Troubleshooting
MSYS2 is installed, but g++ and gdb are still not found
You must follow the steps on the MSYS2 website and use the MSYS CLI to install Mingw-w64, which contains those tools.
MinGW 32-bit
If you need a 32-bit version of the MinGW toolset, consult the Downloading section on the MSYS2 wiki. It includes links to both 32-bit and 64-bit installation options.
C/C++ support for Visual Studio Code is provided by a Microsoft C/C++ extension to enable cross-platform C and C++ development on Windows, Linux, and macOS.
Install the extension
- Open VS Code.
- Select the Extensions view icon on the Activity bar or use the keyboard shortcut ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ).
- Search for 'C++' .
- Select Install.
After you install the extension, when you open or create a *.cpp file, you will have syntax highlighting (colorization), smart completions and hovers (IntelliSense), and error checking.
Install a compiler
C++ is a compiled language meaning your program's source code must be translated (compiled) before it can be run on your computer. VS Code is first and foremost an editor, and relies on command-line tools to do much of the development workflow. The C/C++ extension does not include a C++ compiler or debugger. You will need to install these tools or use those already installed on your computer.
There may already be a C++ compiler and debugger provided by your academic or work development environment. Check with your instructors or colleagues for guidance on installing the recommended C++ toolset (compiler, debugger, project system, linter).
Some platforms, such as Linux or macOS, have a C++ compiler already installed. Most Linux distributions have the GNU Compiler Collection (GCC) installed and macOS users can get the Clang tools with Xcode.
Check if you have a compiler installed
Make sure your compiler executable is in your platform path ( %PATH on Windows, $PATH on Linux and macOS) so that the C/C++ extension can find it. You can check availability of your C++ tools by opening the Integrated Terminal ( ⌃` (Windows, Linux Ctrl+` ) ) in VS Code and trying to directly run the compiler.
Checking for the GCC compiler g++ :
Checking for the Clang compiler clang :
Note: If you would prefer a full Integrated Development Environment (IDE), with built-in compilation, debugging, and project templates (File > New Project), there are many options available, such as the Visual Studio Community edition.
If you don't have a compiler installed, in the example below, we describe how to install the Minimalist GNU for Windows (MinGW) C++ tools (compiler and debugger). MinGW is a popular, free toolset for Windows. If you are running VS Code on another platform, you can read the C++ tutorials, which cover C++ configurations for Linux and macOS.
Example: Install MinGW-x64
We will install Mingw-w64 via MSYS2, which provides up-to-date native builds of GCC, Mingw-w64, and other helpful C++ tools and libraries. You can download the latest installer from the MSYS2 page or use this link to the installer.
Follow the Installation instructions on the MSYS2 website to install Mingw-w64. Take care to run each required Start menu and pacman command, especially Step 7, when you will install the actual Mingw-w64 toolset ( pacman -S --needed base-devel mingw-w64-x86_64-toolchain ).
Add the MinGW compiler to your path
Add the path to your Mingw-w64 bin folder to the Windows PATH environment variable by using the following steps:
- In the Windows search bar, type 'settings' to open your Windows Settings.
- Search for Edit environment variables for your account.
- Choose the Path variable in your User variables and then select Edit.
- Select New and add the Mingw-w64 destination folder path, with \mingw64\bin appended, to the system path. The exact path depends on which version of Mingw-w64 you have installed and where you installed it. If you used the settings above to install Mingw-w64, then add this to the path: C:\msys64\mingw64\bin .
- Select OK to save the updated PATH. You will need to reopen any console windows for the new PATH location to be available.
Check your MinGW installation
To check that your Mingw-w64 tools are correctly installed and available, open a new Command Prompt and type:
If you don't see the expected output or g++ or gdb is not a recognized command, make sure your PATH entry matches the Mingw-w64 binary location where the compiler tools are located.
Hello World
To make sure the compiler is installed and configured correctly, we'll create the simplest Hello World C++ program.
Create a folder called "HelloWorld" and open VS Code in that folder ( code . opens VS Code in the current folder):
The "code ." command opens VS Code in the current working folder, which becomes your "workspace". Accept the Workspace Trust dialog by selecting Yes, I trust the authors since this is a folder you created.
Now create a new file called helloworld.cpp with the New File button in the File Explorer or File > New File command.
Add Hello World source code
Now paste in this source code:
Now press ⌘S (Windows, Linux Ctrl+S ) to save the file. You can also enable Auto Save to automatically save your file changes, by checking Auto Save in the main File menu.
Build Hello World
Now that we have a simple C++ program, let's build it. Select the Terminal > Run Build Task command ( ⇧⌘B (Windows, Linux Ctrl+Shift+B ) ) from the main menu.
This will display a dropdown with various compiler task options. If you are using a GCC toolset like MinGW, you would choose C/C++: g++.exe build active file.
This will compile helloworld.cpp and create an executable file called helloworld.exe , which will appear in the File Explorer.
Run Hello World
From a command prompt or a new VS Code Integrated Terminal, you can now run your program by typing ".\helloworld".
If everything is set up correctly, you should see the output "Hello World".
This has been a very simple example to help you get started with C++ development in VS Code. The next step is to try one of the tutorials listed below on your platform (Windows, Linux, or macOS) with your preferred toolset (GCC, Clang, Microsoft C++) and learn more about the Microsoft C/C++ extension's language features such as IntelliSense, code navigation, build configuration, and debugging.
Tutorials
Get started with C++ and VS Code with tutorials for your environment:
Documentation
You can find more documentation on using the Microsoft C/C++ extension under the C++ section of the VS Code website, where you'll find topics on:
Remote Development
VS Code and the C++ extension support Remote Development allowing you to work over SSH on a remote machine or VM, inside a Docker container, or in the Windows Subsystem for Linux (WSL).
To install support for Remote Development:
- Install the VS Code Remote Development Extension Pack.
- If the remote source files are hosted in WSL, use the Remote - WSL extension.
- If you are connecting to a remote machine with SSH, use the Remote - SSH extension.
- If the remote source files are hosted in a container (for example, Docker), use the Remote - Containers extension.
Feedback
If you run into any issues or have suggestions for the Microsoft C/C++ extension, please file issues and suggestions on GitHub. If you haven't already provided feedback, please take this quick survey to help shape this extension for your needs.
Читайте также: