C/C++ for Visual Studio Code
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.
You will need to install the full Mingw-w64 toolchain ( pacman -S —needed base-devel mingw-w64-x86_64-toolchain ) to get the gdb debugger.
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.
If the compilers do not exist at that PATH entry, make sure you followed the instructions on the MSYS2 website to install Mingw-w64.
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 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 Dev Containers extension.
Enhance completions with AI
GitHub Copilot is an AI-powered code completion tool that helps you write code faster and smarter. You can use the GitHub Copilot extension in VS Code to generate code, or to learn from the code it generates.
GitHub Copilot provides suggestions for numerous languages and a wide variety of frameworks, and it works especially well for Python, JavaScript, TypeScript, Ruby, Go, C# and C++.
You can learn more about how to get started with Copilot in the Copilot documentation.
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.
Name already in use
vscode-docs / docs / languages / cpp.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
C/C++ for Visual Studio Code
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 ( kb(workbench.view.extensions) ).
- 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 ( kb(workbench.action.terminal.toggleTerminal) ) 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.
You will need to install the full Mingw-w64 toolchain ( pacman -S —needed base-devel mingw-w64-x86_64-toolchain ) to get the gdb debugger.
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.
If the compilers do not exist at that PATH entry, make sure you followed the instructions on the MSYS2 website to install Mingw-w64.
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 kb(workbench.action.files.save) 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 ( kb(workbench.action.tasks.build) ) 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.
Get started with C++ and VS Code with tutorials for your environment:
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:
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 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 Dev Containers extension.
Enhance completions with AI
GitHub Copilot is an AI-powered code completion tool that helps you write code faster and smarter. You can use the GitHub Copilot extension in VS Code to generate code, or to learn from the code it generates.
GitHub Copilot provides suggestions for numerous languages and a wide variety of frameworks, and it works especially well for Python, JavaScript, TypeScript, Ruby, Go, C# and C++.
You can learn more about how to get started with Copilot in the Copilot documentation.
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.
Первая программа
Д ля начала, необходимо установить программное обеспечение. В принципе не важно, каким ПО вы будете пользоваться, также как не важна и операционная система. Но в течение всего курса я буду приводить примеры на MS Visula Studio 2012 Express Edition. Visual Studio 2012 Express Edition бесплатный и его за глаза хватит для изучения всего курса. Кроме того, как показала практика, он гораздо строже относится к коду и даёт более полноценное описание ошибок и предупреждений. При изучении языка можно использовать Borland (он же CodeGEAR, он же Embarcadero и т.д.), Dev Cpp, MinGW, или gcc, или что вы ещё захотите.
Пример для MS Visual Studio
1. Открываем IDE, заходим Файл | Создать проект.
2. Выбираем консольное приложение и даём ему имя. В данном случае first_program
4. Ставим галочку «Пустой проект».
5. После чего получаем пустую структуру проекта. Добавим новый элемент: правый клик мыши по папке
«Файлы исходного кода» | Добавить | Создать элемент.
Добавляем новый cpp файл, но сохраняем его с расширением .c
Я назвал файл main.c Всё, готово, можно писать программу. Пропустите шаги для других платформ.
Borland
У меня установлен только Code Gear C++Builder 2007, но в остальных (и предыдущих) релизах всё делается также.
1. Создадим новый проект File | New | Other.
2. Добавляем консольное приложение
3. Выбираем язык си
4. Получаем готовый проект. Его необходимо сохранить с тем именем, которое захотите. До тех пор сам проект и все файлы будут иметь имена по умолчанию. Вы можете удалить то, что Borland по умолчанию прописал в тексте программы.
Пример для cc/gcc для терминала
О ткройте ваш любимый текстовый редактор и скопируйте туда код программы.
Если вы сохранили программу в файле с именем hello.c, то наберите в терминале команду
cc hello.c -o hello
либо
gcc hello -o hello
При этом, очевидно, вы должны находиться в папке с программой. gcc создаст исполняемый файл с именем hello. Запустите его, и он выведет Hello, World!
./hello
Иногда могут возникнуть проблемы с правами доступа. Проверьте, что у вас исполняемый файл, иначе дайте себе привелегии на запуск.
chmod 760 hello
Если у вас несколько файлов, то необходимо будет перечислить имена всех си файлов по порядку. Например, если у вас есть ещё два файла simple.h и simple.c, то нужно прописать
cc hello.c simple.c -o hello
Код программы
Принято в первой программе выводить Hello, World! на экран.
Запустите программу ( Run | Run или F9 для борланда, Построение | Построить решение или F5 для MS) Программа выведет Hello, World! и будет ждать, когда вы нажмёте на любую клавишу.
Рассмотрим код подробнее. Первые две строки
директивы компилятору на подключение стандартных библиотек stdio (Standard Input Output — стандартная библиотека ввода вывода) и conio (Console Input Output — стандартная библиотека консоли вывода вывода). Расширение .h указывает, что это заголовочные файлы (header files). Компилятор копирует код библиотек conio и stdio, и даёт возможность использовать функции, описанные в этих библиотеках.
Это функция main. Она отличается от остальных функций, которые вы можете определить тем, что является точкой входа — с неё начинается выполнение программы.
Функция main имеет два параметра — число параметров argc и массив переданных параметров argv. Эти аргументы необязательные, поэтому можно их не писать. Об их использовании поговорим позже. Функция main должна возвращать целое число. Если это 0, то функция отработала без ошибок. В современном стандарте си можно не возвращать 0, и описать функцию как void main. Наша программа теперь выглядит совсем просто. Строка выводит строку Hello, World! на экран монитора. ожидает нажатия на клавишу.
Давайте сделаем что-нибудь посложнее, чтобы научиться добавлять новые файлы в программу. Сейчас для вас важно научиться добавлять новые файлы, если часть кода останется непонятной, это не беда.
1. Создайте новый заголовочный файл в папке «Заголовочные файлы», назовите его simple.h
2. Создайте новый файл simple.c в папке «Файлы исходного кода».
3. Добавьте в simple.h
Здесь мы объявили новую функцию doSomething. У неё отсутствует тело, оно будет описано в файле simple.c. Здесь же мы подключаем и библиотеки stdio и conio
Добавьте в simple .c
Мы включаем в файл simple.c заголовочный файл. Он пишется в двойных кавычках, потому что это не файл из стандартной библиотеки. Файлы стандартной библиотеки обычно располагаются в папке include самой IDE. Если поместить туда наши файлы, то их тоже можно будет объявлять в угловых скобках. В двойных кавычках можно также прописывать абсолютные пути к файлам. Так как мы уже включили библиотеки conio и stdio в .h файле, то они «видны» и в .c файле.
Далее, в main.c
Мы подключаем только заголовочный файл. Содержимое simple.c будет добавлено автоматически. Собираем проект (F5 или F9, или что там у вас за среда. ) Если у вас всё заработало то отлично, вы научились добавлять новые файлы в проект.
Всё ещё не понятно? – пиши вопросы на ящик
Как настроить Visual Studio Code для C, C++, Java, Python
Visual Studio Code — популярный редактор кода, бесплатный и с открытым исходным кодом. Но я уверен: каждый из нас, кто пытался настроить Visual Studio Code для разработки приложений на C++, Java или Python, прошел через стадию: “О Боже! Почему нельзя как-нибудь попроще?” Я сам пробовал настроить VS Code пару раз и в итоге закончил тем, что использовал CodeBlocks.
Прочитав много документации, посмотрев ряд роликов на YouTube и потратив несколько дней на саму настройку VS Code, я пишу эту статью, чтобы все это не пришлось проделывать уже вам!
Сегодня я покажу, как настроить среду разработки для спортивного программирования на C++, Java и Python в VS Code с нуля. Мы также посмотрим, какие расширения больше всего пригодятся, чтобы начать работу с VS Code. В конечном счете, ваша среда разработки будет выглядеть примерно так:
1. Устанавливаем Visual Studio Code
Скачайте последнюю версию Visual Studio Code с официального сайта. Рекомендуется загрузить системный установщик (System Installer), но если у вас нет прав администратора, то пользовательский установщик (User Installer) тоже подойдет. Выполните все обычные шаги по установке и обязательно проставьте все следующие чекбоксы:
Если у вас уже установлен VS Code, но вы все равно хотите начать с чистого листа, следуйте этим инструкциям, чтобы полностью удалить VS Code.
2. Настраиваем расширения
Ниже приведен список расширений, которые нам понадобятся для правильной настройки VS Code. Откройте VS Code и перейдите на панель расширений (Ctrl + Shift + X), которая находится на левой панели инструментов, и начните загружать друг за другом следующие расширения:
-
от Microsoft — [Важно] Для корректной работы этого расширения нам понадобится установленный и добавленный в PATH компилятор MinGW. Если у вас его нет, следуйте этому руководству. от austin. от Microsoft — вам нужно будет настроить Python для работы этого расширения. Загрузите и установите последнюю версию отсюда. от Microsoft — [Важно] Перед установкой убедитесь, что в вашей системе настроены Java 8 JDK и JRE и указаны все необходимые переменные среды для Java. Если нет, посмотрите это видео о том, как настроить Java на вашем компьютере. от Jun Han — мы будем использовать это расширение для запуска всех наших программ. Для этого необходимо выполнить некоторые шаги по настройке. Мы увидим эти шаги в следующих разделах.
Расширения, перечисленные ниже, необязательны для дальнейшей настройки, но я рекомендую вам обратить на них внимание, посмотреть, заинтересуют ли они вас, и если нет, то перейти к следующему разделу.
- (Необязательно)Material Theme от Mattia Astronio — это расширение содержит множество приятных глазу тем. Вы можете выбрать любую, какая понравится. Лично я предпочитаю Monokai, которая доступна в VS Code по умолчанию, без каких-либо расширений.
Чтобы выбрать тему, нажмите Ctrl + Shift + P. Откроется палитра команд. Осуществите поиск по слову “theme” и выберите опцию Color Theme. Чтобы настроить иконки, можете выбрать опцию File Icon Theme.
Расширения для тех, кто интересуется FrontEnd-фреймворками для веб-разработки, такими как Angular и React:
- (Необязательно) Angular Language Service от Angular.
- (Необязательно) Angular Snippets от John Papa.
- (Необязательно) ES7 React / Redux / GraphQL / React-Native snippets от dsznajder.
- (Необязательно) React Native Tools от Microsoft.
- (Необязательно) Live Server от Ritwick Dey.
3. Настраиваем внешний вид редактора
Итак, мы уже установили VS Code и несколько расширений. Теперь мы готовы настраивать среду разработки. Я создал шаблон для спортивного программирования в VS Code и загрузил его в свой профиль на Github.
Перейдите по этой ссылке и загрузите шаблон себе на компьютер. Распакуйте его в любое место по вашему выбору. После этого откройте получившуюся папку в VS Code. Вы должны увидеть что-то вроде этого:
Пройдитесь по файлам main.cpp, Main.java и main.py и посмотрите на записанный в них образец кода. По сути, шаблонный код, предоставленный в образцах для каждого из этих трех языков, принимает входящие данные из файла input.txt и обеспечивает вывод в файл output.txt. Для каждой программистской задачи, которую вы хотите решить, просто создайте копию этого шаблона и напишите свой код в функции solve().
Теперь создадим ту разбивку экрана, которую вы могли видеть на самом первом изображении в этой статье. Эта разбивка позволяет сразу видеть как ввод, так и вывод вашего кода, что делает ее очень удобной в использовании.
- Откройте файлы в следующем порядке: main.cpp, input.txt, output.txt. Порядок, в каком были открыты файлы, можно видеть сверху на панели инструментов. Убедитесь, что порядок именно такой, как указано выше.
- Откройте input.txt. Выберите в меню View -> Editor Layout -> Split Right. Вы должны увидеть что-то подобное:
- У вас получится две группы. Перетащите output.txt из левой группы в правую. Закройте тот input.txt, что остался слева. Должно выйти примерно так:
- Далее откройте output.txt в правой группе. Выберите View -> Editor Layout -> Split Down. Уберите output.txt из верхней группы. После этого вы увидите:
Готово! Мы настроили внешний вид редактора. А теперь давайте запускать код.
4. Запускаем код!
Для запуска нашего кода мы будем использовать расширение Code Runner, потому что ручная настройка VS Code для каждого языка — весьма сложная задача и потребует много затрат времени и сил.
Прежде чем использовать это расширение, нам нужно настроить его так, чтобы оно работало через терминал, иначе мы не сможем обеспечить консольный ввод нашего кода. Эти шаги очень важно проделать в точности:
- Выберите File -> Preferences -> Settings.
- Введите “code runner run in terminal” в поле поиска и установите галку в чекбоксе:
- Добавьте флаг -std=c++14.
По умолчанию Code Runner не добавляет флаг -std=c++14 при компиляции кода. Это ограничивает ваши возможности как программиста. Например, если вы попытаетесь сделать так:
То это вызовет предупреждение: “Расширенные списки инициализаторов доступны только с -std=c++11 или -std=gnu++11”.
Выполните следующие действия, чтобы добавить флаг:
- Выберите File -> Preferences -> Settings.
- Введите в поиске “Run Code Configuration”.
- Определите местонахождение “Code-runner: Executor Map” и выберите “Edit in settings.json”. Это откроет файл settings.json. Добавьте туда следующий код:
- Сохраните изменения — и готово!
Наконец-то всё настроено для запуска ваших программ на C++, Java и Python.
Откройте файл main.cpp. Нажмите правую кнопку мыши и выберите опцию Run Code. Попробуйте напечатать что-нибудь в функции solve(), чтобы проверить, происходит ли у вас вывод в файл output.txt или нет.
Следуйте той же процедуре с файлами Main.java и main.py. Расширение Code Runner возьмет на себя выполнение каждого из них.
Я надеюсь, что эта статья помогла вам настроить Visual Studio Code. Счастливого программирования!