Как компилировать в visual studio code
В состав Visual C++ включен компилятор языка C, позволяющий создавать как простые консольные программы, так и классические приложения Windows, мобильные приложения и многое другое.
В этом пошаговом руководстве показано, как создать простейшую программу на языке C в стиле "Hello, World" в текстовом редакторе с последующей компиляцией из командной строки. Если вы предпочитаете работать с C++ в командной строке, см. статью Пошаговое руководство. Компиляция собственной программы на языке C++ из командной строки. Если вы хотите попробовать интегрированную среду разработки Visual Studio вместо командной строки, см. статью Пошаговое руководство. Работа с проектами и решениями (C++) или Использование интегрированной среды разработки Visual Studio для разработки приложений для настольных систем на языке C++.
Предварительные требования
Для выполнения этого пошагового руководства необходимо установить Visual Studio и дополнительные компоненты Visual C++ или Build Tools для Visual Studio.
Visual Studio — это эффективная интегрированная среда разработки, которая поддерживает полнофункциональный редактор, диспетчеры ресурсов, отладчики и компиляторы для многих языков и платформ. Сведения об этих компонентах, а также о скачивании и установке Visual Studio, включая бесплатный выпуск Visual Studio Community, см. в этой статье.
При использовании версии Build Tools для Visual Studio устанавливаются только программы командной строки, библиотеки и компиляторы, необходимые для сборки программ на C и C++. Это идеальный вариант для создания заданий и упражнений, а установка выполняется относительно быстро. Чтобы установить только набор программ командной строки, скачайте Build Tools для Visual Studio на странице скачивания Visual Studio, а затем запустите установщик. В установщике Visual Studio выберите рабочую нагрузку Средства сборки C++ и щелкните Установить.
Прежде чем можно будет выполнить сборку программы C или C++ в командной строке, необходимо убедиться в том, что эти средства установлены и к ним можно получить доступ из командной строки. Visual C++ имеет сложные требования к среде командной строки для поиска используемых средств, заголовков и библиотек. Visual C++ нельзя использовать в простом окне командной строки без предварительной подготовки. Вам понадобится окно командной строки разработчика, являющееся обычным окном командной строки, в котором заданы все необходимые переменные среды. К счастью, Visual C++ устанавливает ярлыки для запуска командной строки разработчика, для которой настроена среда для сборок из командной строки. К сожалению, имена ярлыков командной строки разработчика и места их расположения отличаются практически во всех версиях Visual C++ и в различных версиях Windows. Первая задача пошагового руководства — найти нужный ярлык.
Ярлык командной строки разработчика автоматически задает правильные пути для компилятора и средств, а также для всех необходимых заголовков и библиотек. Некоторые из этих значений различаются для каждой конфигурации сборки. Если вы не используете ни один из ярлыков, эти значения среды необходимо задать самостоятельно. Дополнительные сведения см. в статье Использование набора инструментов MSVC из командной строки. Так как настраивать среду разработки сложно, настоятельно рекомендуется использовать ярлык командной строки разработчика вместо создания собственного.
Инструкции отличаются в зависимости от используемой версии Visual Studio. Чтобы ознакомиться с документацией по предпочтительной версии Visual Studio, используйте селектор Версия. Он находится в верхней части оглавления на этой странице.
Открытие командной строки разработчика в Visual Studio 2022
Если вы установили Visual Studio 2022 в Windows 10 или более поздней версии, откройте меню "Пуск" и выберите Все приложения. Прокрутите вниз и откройте папку Visual Studio 2022 (не приложение Visual Studio 2022). Выберите элемент Командная строка разработчика для VS 2022, чтобы открыть окно командной строки.
Открытие командной строки разработчика в Visual Studio 2019
Если вы установили Visual Studio 2019 в Windows 10 или более поздней версии, откройте меню "Пуск" и выберите Все приложения. Прокрутите вниз и откройте папку Visual Studio 2019 (не приложение Visual Studio 2019). Выберите элемент Командная строка разработчика для VS 2019, чтобы открыть окно командной строки.
Открытие командной строки разработчика в Visual Studio 2017
Если вы установили Visual Studio 2017 в Windows 10 или более поздней версии, откройте меню "Пуск" и выберите Все приложения. Прокрутите вниз и откройте папку Visual Studio 2017 (не приложение Visual Studio 2017). Выберите элемент Командная строка разработчика для VS 2017, чтобы открыть окно командной строки.
Открытие командной строки разработчика в Visual Studio 2015
Если вы установили Microsoft Visual C++ Build Tools 2015 в Windows 10 или более поздней версии, откройте меню "Пуск" и выберите Все приложения. Прокрутите вниз и откройте папку Microsoft Visual C++ Build Tools. Выберите элемент Командная строка Native Tools x86 Visual C++ 2015, чтобы открыть окно командной строки.
Если вы используете другую версию Windows, найдите в меню "Пуск" или на начальной странице папку средств Visual Studio, содержащую ярлык командной строки разработчика. Можно также ввести "командная строка разработчика" в строке поиска в Windows и выбрать командную строку, которая соответствует установленной версии Visual Studio. Откройте окно командной строки с помощью ярлыка.
Затем убедитесь в том, что командная строка разработчика Visual C++ настроена правильно. В окне командной строки введите cl (или CL не имеет значения для имени компилятора, но имеет значение для параметров компилятора). Результат должен выглядеть следующим образом.
В зависимости от установленной версии Visual C++ и обновлений текущий каталог или номера версий могут отличаться. Если приведенный выше результат похож на отображаемый, можно приступать к сборке программ C или C++ в командной строке.
В зависимости от версии Windows, установленной на компьютере, и конфигурации системы безопасности может потребоваться правой кнопкой мыши открыть контекстное меню для ярлыка командной строки разработчика и выбрать пункт Запуск от имени администратора, чтобы успешно выполнить сборку и запуск программы, созданной в этом пошаговом руководстве.
Создание файла исходного кода на языке C и его компиляция из командной строки
В окне командной строки разработчика введите команду cd c:\ , чтобы изменить текущий рабочий каталог на корень диска C:. Затем введите md c:\hello , чтобы создать каталог, и введите cd c:\hello , чтобы перейти к этому каталогу. В этом каталоге будут находиться исходный файл и скомпилированная программа.
В командной строке разработчика введите команду notepad hello.c . В появившемся диалоговом окне блокнота с оповещением выберите Да, чтобы создать файл hello.c в рабочей папке.
В окне блокнота введите следующие строки кода:
В строке меню блокнота выберите Файл>Сохранить, чтобы сохранить файл hello.c в рабочей папке.
Вернитесь к окну командной строки разработчика. Введите dir в командной строке, чтобы получить список содержимого каталога c:\hello . Вы увидите исходный файл hello.c в списке каталогов, который выглядит примерно так:
Даты и некоторые другие данные будут отличаться на вашем компьютере. Если вы не видите файл исходного кода hello.c , убедитесь в том, что вы открыли созданный каталог c:\hello и сохранили исходный файл в нем в блокноте. Также убедитесь, что исходный код был сохранен с расширением имени файла .c , а не .txt .
Чтобы скомпилировать программу, в командной строке разработчика введите cl hello.c .
Имя исполняемой программы (hello.exe) отображается в информации, выводимой компилятором.
Чтобы запустить программу, в командной строке введите hello .
Программа выводит следующий текст и затем закрывается:
Поздравляем! Вы скомпилировали и запустили программу на C с помощью командной строки.
Следующие шаги
Этот пример Hello, World является самой простой программой C. Реальные программы выполняют полезные действия и имеют файлы заголовков, дополнительные исходные файлы и ссылки на библиотеки.
Вы можете использовать шаги, описанные в этом пошаговом руководстве для C, для создания собственного кода, чтобы не вводить приведенный пример. Вы также можете выполнить сборку различных примеров кода на C, которые можно найти в других местах. Чтобы скомпилировать программу с дополнительными файлами исходного кода, введите их все в командной строке, например:
cl file1.c file2.c file3.c
Компилятор выдает программу с именем file1.exe. Чтобы изменить имя на program1.exe, добавьте параметр компоновщика /out:
cl file1.c file2.c file3.c /link /out:program1.exe
Чтобы автоматически перехватывать другие ошибки программирования, рекомендуется выполнить компиляцию с помощью порога предупреждений /W3 или /W4:
cl /W4 file1.c file2.c file3.c /link /out:program1.exe
Компилятор cl.exe имеет множество других параметров, которые можно применять для создания, оптимизации, отладки и анализа кода. Чтобы просмотреть краткий список, введите cl /? в командной строке разработчика. Можно также выполнять компиляцию и компоновку отдельно и применять параметры компоновщика в более сложных сценариях сборки. Дополнительные сведения о параметрах компилятора и компоновщика и использовании см. в разделе Справочник по построению C/C++.
Для настройки и создания более сложных проектов в командной строке можно использовать NMAKE и файлы makefile либо MSBuild и файлы проекта. Дополнительные сведения об использовании этих средств см. в разделах Справочник по NMAKE и MSBuild.
Языки C и C++ похожи, но имеют различия. Компилятор Microsoft C/C++ (MSVC) использует простое правило для определения языка, используемого при компиляции кода. По умолчанию компилятор MSVC рассматривает все файлы с расширением .c как исходные коды на языке С, а файлы с расширением .cpp как исходные коды на языке С++. Если указан параметр компилятора /TC, компилятор будет рассматривать все файлы как исходные коды на языке С вне зависимости от расширения.
Компилятор MSVC совместим со стандартами ANSI C89 и ISO C99, но не полностью. В большинстве случаев переносимый код на языке C будет компилироваться и выполняться должным образом. Компилятор обеспечивает дополнительную поддержку изменений в ISO C11/C17. Чтобы выполнить компиляцию с поддержкой C11/C17, используйте флаг компилятора /std:c11 или /std:c17 . Для поддержки C11 и C17 требуется Windows SDK 10.0.20201.0 или более поздняя версия. Рекомендуется использовать Windows SDK 10.0.22000.0 или более позднюю версию. Последнюю версию пакета можно скачать на странице Windows SDK. Дополнительные сведения и инструкции по установке и использованию этого пакета SDK для разработки на языке C см. в статье Установка поддержки C11 и C17 в Visual Studio.
Некоторые функции библиотеки и имена функций POSIX являются нерекомендуемыми в компиляторе MSVC. Функции поддерживаются, но предпочтительные имена изменились. Дополнительные сведения см. в статьях Функции безопасности в CRT и Предупреждение компилятора (уровень 3) C4996.
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.
Предварительные требования
Создание приложения
Запустите Visual Studio Code.
В главном меню выберите Файл>Открыть папку (в macOS выберите File>Open. (Файл > Открыть)).
В диалоговом окне Открыть папку создайте папку HelloWorld и выберите ее. Затем щелкните Выбрать папку (или Открыть в macOS).
Имя папки по умолчанию преобразуется в имя проекта и имя пространства имен. Вы добавите код позже в этом учебнике. Предполагается, что пространство имен проекта — HelloWorld .
В диалоговом окне о доверии авторам файлов в этой папке выберите Да, я доверяю авторам.
Откройте терминал в Visual Studio Code, выбрав в основном меню пункт Вид>Терминал.
Откроется окно Терминал с командной строкой в папке HelloWorld.
В окне терминала введите следующую команду:
Шаблон проекта создает простое приложение, которое отображает "Hello World" в окне консоли, вызывая метод Console.WriteLine(String) из файла Program.cs.
Замените содержимое Program.cs кодом из этого примера.
При первом редактировании файла .cs в Visual Studio Code будет предложено добавить недостающие ресурсы для сборки и отладки приложения. Выберите Да и Visual Studio Code создаст папку .vscode с файлами launch.json и tasks.json.
Если запрос не отображается или вы случайно закрываете его без нажатия кнопки "Да", выполните следующие действия, чтобы создать launch.json и tasks.json:
- Выберите "КонфигурацияRunAdd>" в меню.
- Выберите .NET 5+ и .NET Core в командной строке "Выбор среды ".
Код определяет класс Program с одним методом Main , который принимает массив String в качестве аргумента. Main — точка входа в приложение. Это метод, который автоматически вызывается средой выполнения при запуске приложения. Все аргументы, предоставленные в командной строке при запуске приложения, доступны через массив args.
Запуск приложения
Выполните следующие команды в окне терминала:
Программа отображает "Hello World!" и заканчивается.
Улучшение приложения
Давайте расширим приложение. Теперь у пользователя будет запрашиваться имя, которое затем будет отображаться с датой и временем.
Откройте файл Program.cs.
В Program.cs замените содержимое метода Main (строка, вызывающая Console.WriteLine ) следующим кодом:
Этот код отображает запрос в окне консоли и ожидает, чтобы пользователь ввел строку текста и нажал клавишу ВВОД . Приложение сохраняет полученную строку в переменной с именем name . Оно также получает значение свойства DateTime.Now, которое содержит текущее локальное время, и присваивает его переменной с именем currentDate . Затем оно отображает эти значения в окне консоли. Наконец, приложение выводит запрос в окне консоли и вызывает метод Console.ReadKey(Boolean) для ожидания ввода данных пользователем.
Знак доллара ( $ ) перед строкой позволяет вставить такие выражения, как имена переменных, в фигурные скобки в строке. Значение выражения вставляется в строку вместо выражения. Такой синтаксис называется интерполированными строками.
В Visual Studio Code необходимо явно сохранить изменения. В отличие от Visual Studio, изменения файлов не сохраняются автоматически при сборке и запуске приложения.
Запустите программу еще раз:
В ответ на приглашение в командной строке введите имя и нажмите клавишу ВВОД .
Нажмите любую клавишу для выхода из программы.
Дополнительные ресурсы
Следующие шаги
Предварительные требования
Создание приложения
Запустите Visual Studio Code.
В главном меню выберите Файл>Открыть папку (в macOS выберите File>Open. (Файл > Открыть)).
В диалоговом окне Открытие папки создайте папку HelloWorld и щелкните Выбрать папку (в macOS щелкните Open (Открыть)).
Имя папки по умолчанию преобразуется в имя проекта и имя пространства имен. Вы добавите код позже в этом учебнике. Предполагается, что пространство имен проекта — HelloWorld .
Откройте терминал в Visual Studio Code, выбрав в основном меню пункт Вид>Терминал.
Откроется окно Терминал с командной строкой в папке HelloWorld.
В окне терминала введите следующую команду:
Этот шаблон создает простое приложение Hello World. Он вызывает метод Console.WriteLine(String) для вывода "Hello World!" в окне консоли.
Код шаблона определяет класс Program с одним методом Main , который принимает в качестве аргумента массив String.
Main — точка входа в приложение. Это метод, который автоматически вызывается средой выполнения при запуске приложения. Все аргументы, предоставленные в командной строке при запуске приложения, доступны через массив args.
Запуск приложения
Выполните следующие команды в окне терминала:
Программа отображает "Hello World!" и заканчивается.
Улучшение приложения
Давайте расширим приложение. Теперь у пользователя будет запрашиваться имя, которое затем будет отображаться с датой и временем.
Откройте файл Program.cs, щелкнув его.
Когда в Visual Studio Code будет предложено добавить недостающие ресурсы для сборки и отладки приложения, выберите Да.
В Program.cs замените содержимое метода Main (строка, вызывающая Console.WriteLine ) следующим кодом:
Этот код отображает запрос в окне консоли и ожидает, чтобы пользователь ввел строку текста и нажал клавишу ВВОД . Приложение сохраняет полученную строку в переменной с именем name . Оно также получает значение свойства DateTime.Now, которое содержит текущее локальное время, и присваивает его переменной с именем currentDate . Затем оно отображает эти значения в окне консоли. Наконец, приложение выводит запрос в окне консоли и вызывает метод Console.ReadKey(Boolean) для ожидания ввода данных пользователем.
Знак доллара ( $ ) перед строкой позволяет вставить такие выражения, как имена переменных, в фигурные скобки в строке. Значение выражения вставляется в строку вместо выражения. Такой синтаксис называется интерполированными строками.
В Visual Studio Code необходимо явно сохранить изменения. В отличие от Visual Studio, изменения файлов не сохраняются автоматически при сборке и запуске приложения.
Запустите программу еще раз:
В ответ на приглашение в командной строке введите имя и нажмите клавишу ВВОД .
Нажмите любую клавишу для выхода из программы.
Дополнительные ресурсы
Следующие шаги
Поскольку мне всё равно пришлось ставить Visual Studio Community для того, чтобы установить Windows Kits для работы с WinAPI, то я решил не использовать MingW, а доустановить C++ build tools и использовать их для компиляции. В этом случае придётся переделать задачи (tasks) и настройки VSCode.
Хорошее описание нашёл здесь, его и буду использовать в данной заметке.
Нам потребуется
1. Естественно нам потребуется сама программа VSCode.
2. В Visual Studio Community должен быть установлен компонент Desktop development with C++ :
Чтобы проверить успешную установку, достаточно вызвать Developer Command Prompt for VS 2019 (файл VsDevCmd.bat ) из Пуска. Там нужно запустить файл cl.exe . Вывод консоли должен быть без ошибок:
3. Для VSCode должно быть установлено дополнение (расширение) Microsoft C/C++
Настройка
4. В Проводнике открываем рабочую папку проекта и, удерживая Shift , нажимаем правую кнопку мыши, после чего выбираем Open PowerShell window here
5. В открывшемся окошке PowerShell запускаем VSCode, для этого нужно набрать code . и нажать Enter :
6. В запущенном редакторе создадим новый файл:
File ▶ New File Ctrl + N
7. Это просто тест, поэтому код будет простейшим:
8. Сохраним файл под именем main.cpp :
File ▶ Save As…
Шаги 9-11 скорее всего не нужны. В статье они есть, но без них у меня всё тоже прекрасно компилируется.
9. Открываем палитру команд с помощью комбинации клавиш Ctrl + Shift + P
10. Список большой, поэтому проще ввести часть слова и выбрать нужную команду Edit Configurations UI из списка:
11. В конфигурации необходимо проверить, а, при необходимости, установить путь для компилятора:
12. Внесём изменения в файл settings.json :
У меня глобальный файл настроек, а не только для проекта, поэтому я добавляю строчки в начало файла C:\Users\Denis\AppData\Roaming\Code\User\settings.json
13. Ранее я уже создавал файл Задач tasks.json, поэтому сейчас я добавлю к нему новые строчки:
~ Missing '(' after 'if' in if statement.
CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
FullyQualifiedErrorId : MissingOpenParenthesisInIfStatement
В этом случае фрагмент кода с проверкой пути должен быть таким:
Хотя, если у вас VSCode настроен для работы с CMD, а не PowerShell, то ошибки быть не должно!
14. Чтобы у нас была возможность запустить проект на отладку, можно использовать файл launch.json . Но я не хочу создавать такой файл для каждого проекта каждый раз, поэтому сделаю глобальную конфигурацию. Для этого я добавлю строчки в файл settings.json :
Благодаря этому, при нажатии F5 , проект будет откомпилирован, а потом запущен сразу после этого. Просто запустить, без отладки, можно комбинацией Ctrl + F5
Читайте также: