Как работать с visual studio code c на windows

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. When you create a *.cpp file, the extension adds features such as syntax highlighting (colorization), smart completions and hovers (IntelliSense), and error checking.

C++ language features

Install the extension

  1. Open VS Code.
  2. Select the Extensions view icon on the Activity bar or use the keyboard shortcut (⇧⌘X (Windows, Linux Ctrl+Shift+X)).
  3. Search for 'C++'.
  4. Select Install.

C/C++ extension

Set up your C++ Environment

C++ is a compiled language meaning your program’s source code must be translated (compiled) before it can be run on your computer. The C/C++ extension doesn’t include a C++ compiler or debugger, since VS Code as an editor relies on command-line tools for the development workflow. You need to install these tools or use the tools already installed on your computer.

Check if you have a compiler installed

Note: 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).

Common compilers that already come preinstalled on some platforms are the GNU Compiler Collection (GCC) on Linux and the Clang tools with Xcode on macOS.

To check if you already have them installed:

  1. Open a new VS Code terminal window using (⌃⇧` (Windows, Linux Ctrl+Shift+`))

  2. Use the following command to check for the GCC compiler g++:

    g++ --version
    

    Or this command for the Clang compiler clang:

    clang --version
    

The output should show you the compiler version and details. If neither are found, 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. Otherwise, use the instructions in the section below to install a compiler.

Install a compiler

If you don’t have a compiler installed, you can follow one of our installation tutorials:

Windows:

Go to the MSVC tutorial

Go to the MinGW tutorial

Linux:

Go to the GCC tutorial

macOS:

Go to the Clang tutorial

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.

Example: Install MinGW-x64 on Windows

To understand the process, let’s install Mingw-w64 via MSYS2. Mingw-w64 is a popular, free toolset on Windows. It provides up-to-date native builds of GCC, Mingw-w64, and other helpful C++ tools and libraries.

  1. Download using this direct link to the MinGW installer.

  2. Run the installer and follow the steps of the installation wizard. Note, MSYS2 requires 64 bit Windows 8.1 or newer.

  3. In the wizard, choose your desired Installation Folder. Record this directory for later. In most cases, the recommended directory is acceptable. The same applies when you get to setting the start menu shortcuts step. When complete, ensure the Run MSYS2 now box is checked and select Finish. A MSYS2 terminal window will then automatically open.

  4. In this terminal, install the MinGW-w64 toolchain by running the following command:

    pacman -S --needed base-devel mingw-w64-ucrt-x86_64-toolchain
    
  5. Accept the default number of packages in the toolchain group by pressing Enter.

    MYSS2 Installer

  6. Enter Y when prompted whether to proceed with the installation.

  7. Add the path to your MinGW-w64 bin folder to the Windows PATH environment variable by using the following steps:

    1. In the Windows search bar, type Settings to open your Windows Settings.
    2. Search for Edit environment variables for your account.
    3. In your User variables, select the Path variable and then select Edit.
    4. Select New and add the MinGW-w64 destination folder you recorded during the installation process to the list. If you selected the default installation steps, the path is: C:\msys64\ucrt64\bin.
    5. Select OK to save the updated PATH. For the new PATH to be available, reopen your console windows.
  8. Check that your MinGW-w64 tools are correctly installed and available, open a new Command Prompt and type:

gcc --version
g++ --version
gdb --version

You should see output that states which versions of GCC, g++ and GDB you have installed. If this is not the case, make sure your PATH entry matches the Mingw-w64 binary location where the compiler tools are located or reference the troubleshooting section.

Create a Hello World App

To make sure the compiler is installed and configured correctly, lets create a Hello World C++ program.

Create a C++ file

  1. On Windows, launch a Windows command prompt (Enter Windows command prompt in the Windows search bar). On macOS and Linux, you can enter these commands in the terminal.
  2. Run the following commands. They are creating an empty folder called projects where you can place all your VS Code projects. The next commands create and navigate you to a subfolder called helloworld. From there, you are opening helloworld directly in VS Code using the code command.
mkdir projects
cd projects
mkdir helloworld
cd helloworld
code .

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.

File Explorer New File button

Add Hello World source code

Paste in the following source code:

#include <iostream>

int main()
{
    std::cout << "Hello World" << std::endl;
}

Now press ⌘S (Windows, Linux Ctrl+S) to save the file. You can also enable AutoSave to automatically save your file changes, by checking Auto Save in the main File menu.

Run helloworld.cpp

  1. Make sure you have helloworld.cpp open so it is the active file in your editor.

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

    Screenshot of helloworld.cpp and play button

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

    C++ debug configuration dropdown

You are only prompted to choose a compiler the first time you run helloworld.cpp. This compiler becomes «default» compiler set in your tasks.json file.

  1. After the build succeeds, you should see «Hello World» appear in the integrated Terminal.

    screenshot of program output

Congratulations! You’ve just run your first C++ program in VS Code! The next step is to learn more about the Microsoft C/C++ extension’s language features such as IntelliSense, code navigation, build configuration, and debugging using one of the Tutorials in the next section.

Tutorials

Get started with C++ and VS Code with tutorials for your environment:

  • GCC on Windows via MinGW
  • Microsoft C++ on Windows
  • GCC on Linux
  • GCC on Windows Subsystem For Linux
  • Clang/LLVM on macOS
  • CMake Tools on Linux

Documentation

You can find more documentation on using the Microsoft C/C++ extension under the C++ section of the VS Code website, where you can find articles on:

  • Debugging
  • Editing
  • Settings
  • FAQ

C++ TOC on code.visualstudio.com

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:

  1. Install the VS Code Remote Development Extension Pack.
  2. If the remote source files are hosted in WSL, use the WSL extension.
  3. If you are connecting to a remote machine with SSH, use the Remote — SSH extension.
  4. 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 extension in the VS Code Marketplace

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, you can take this quick survey.

7/24/2023

VSCode

Visual Studio Code — популярный редактор кода, бесплатный и с открытым исходным кодом. Но я уверен: каждый из нас, кто пытался настроить Visual Studio Code для разработки приложений на C++, Java или Python, прошел через стадию: “О Боже! Почему нельзя как-нибудь попроще?” Я сам пробовал настроить VS Code пару раз и в итоге закончил тем, что использовал CodeBlocks. 🙁

Прочитав много документации, посмотрев ряд роликов на YouTube и потратив несколько дней на саму настройку VS Code, я пишу эту статью, чтобы все это не пришлось проделывать уже вам!

Сегодня я покажу, как настроить среду разработки для спортивного программирования на C++, Java и Python в VS Code с нуля. Мы также посмотрим, какие расширения больше всего пригодятся, чтобы начать работу с VS Code. В конечном счете, ваша среда разработки будет выглядеть примерно так:

Давайте приступим!

Скачайте последнюю версию Visual Studio Code с официального сайта. Рекомендуется загрузить системный установщик (System Installer), но если у вас нет прав администратора, то пользовательский установщик (User Installer) тоже подойдет. Выполните все обычные шаги по установке и обязательно проставьте все следующие чекбоксы:

Если у вас уже установлен VS Code, но вы все равно хотите начать с чистого листа, следуйте этим инструкциям, чтобы полностью удалить VS Code.

2. Настраиваем расширения

Ниже приведен список расширений, которые нам понадобятся для правильной настройки VS Code. Откройте VS Code и перейдите на панель расширений (Ctrl + Shift + X), которая находится на левой панели инструментов, и начните загружать друг за другом следующие расширения:

  1. C / C++ от Microsoft — [Важно] Для корректной работы этого расширения нам понадобится установленный и добавленный в PATH компилятор MinGW. Если у вас его нет, следуйте этому руководству.
  2. C++ Intellisense от austin.
  3. Python от Microsoft — вам нужно будет настроить Python для работы этого расширения. Загрузите и установите последнюю версию отсюда.
  4. Java Extension Pack от Microsoft — [Важно] Перед установкой убедитесь, что в вашей системе настроены Java 8 JDK и JRE и указаны все необходимые переменные среды для Java. Если нет, посмотрите это видео о том, как настроить Java на вашем компьютере.
  5. Code Runner от 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 при компиляции кода. Это ограничивает ваши возможности как программиста. Например, если вы попытаетесь сделать так:

vector<vector<int>> temp;temp.push_back({1, 2, 3});

То это вызовет предупреждение: “Расширенные списки инициализаторов доступны только с -std=c++11 или -std=gnu++11”

Выполните следующие действия, чтобы добавить флаг:

  • Выберите File -> Preferences -> Settings.
  • Введите в поиске “Run Code Configuration”.
  • Определите местонахождение “Code-runner: Executor Map” и выберите “Edit in settings.json”. Это откроет файл settings.json. Добавьте туда следующий код:
"code-runner.executorMap": {    "cpp": "cd $dir && g++ -std=c++14 $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt"}
  • Сохраните изменения — и готово!

Наконец-то всё настроено для запуска ваших программ на C++, Java и Python.

Откройте файл main.cpp. Нажмите правую кнопку мыши и выберите опцию Run Code. Попробуйте напечатать что-нибудь в функции solve(), чтобы проверить, происходит ли у вас вывод в файл output.txt или нет.

Следуйте той же процедуре с файлами Main.java и main.py. Расширение Code Runner возьмет на себя выполнение каждого из них.

Я надеюсь, что эта статья помогла вам настроить Visual Studio Code. Счастливого программирования! 

Читайте также:

  • Проекты на Python с помощью Visual Studio Code
  • 10 рекомендаций по ускорению рабочего процесса в Visual Studio Code
  • Как настроить отладчик для Chrome extension в Visual Studio Code

Перевод статьи Chinmay Kulkarni: “How to Setup Visual Studio Code for C, C++, Java, Python | Competitive Programming”

How to Write And Run C and C++ Code in Visual Studio Code

Visual Studio Code (or VS Code for short) is a very common and widely used text editor and IDE (Integrated Development Environment). You can make VS Code very powerful like an IDE using a lot of extensions.

Before approaching the process of running your first C or C++ code on Visual Studio Code, let me guide you through the process and get it all set up based on the operating system you are using on your computer.

C and C++ compilers

For running C or C++ code, you just need to have a valid C/C++ compiler installed on your computer. If you are using a Linux operating system, then there is a high chance that it is already installed on your system. But we need to make sure that it is correctly installed.

For checking whether or not you have the compiler (GCC/G++/MinGW) installed on your system or not, you have to check the compiler version first.

Simply open your terminal and use gcc --version and g++ --version. If you get the version number, then the compiler is already installed on your system.

You can check the version using the same commands on any operating system, whether that is a Windows, Linux, or macOS-based operating system.

If you get feedback on your terminal that it does not know anything about GCC or G++, then you have to install the compiler correctly.

If you are using the most used Windows operating system, then I already have written an in-depth article showing you all the processes step-by-step on freeCodeCamp. Make sure to read the entire article first, as it also contains a complete video to provide you with complete support.

How to Install C and C++ Compilers on Windows

If you want to run C or C++ programs in your Windows operating system, then youneed to have the right compilers. The MinGW compiler is a well known and widely used software for installing GCCand G++ compilers for the C and C++ programming languages. But many devs face difficulties when install…

faviconMd. Fahim Bin AminfreeCodeCamp.org

banner_freeCodeCamp

If you are using another operating system, and you don’t have the compilers installed, then make sure to install them before proceeding.

How to Install VS Code or VS Code Insiders

You have to download Visual Studio Code directly from the official website: https://code.visualstudio.com/.

If you want, you can also install VS Code Insiders, and the same process is applicable for that as well.

Visual Studio Code Insiders is actually the «Insiders» build of Visual Studio Code, which contains all the latest features that are shipped daily. You can think of VS Code as the stable release and the VS Code Insiders as the Insiders release of that.

If you want to experience the latest updates instantly, then you might also try Visual Studio Code Insiders (I use it myself). For downloading VS Code Insiders, you can visit the official website for VS Code Insiders here: https://code.visualstudio.com/insiders/

Make sure to download the exact file for your operating system.

image-163

Download Page: VS Code
image-164
Download Page: VS Code Insiders

The installation process is pretty basic. But I am going to show you all the steps sequentially. For now, I am going to show you the installation process using VS Code Insiders, but everything you will see here is going to be exactly the same for VS Code as well.

Make sure to click the box on the «I accept the agreement » box and click on Next.

image-165

Accept the agreement and click Next

Keep everything as it is. Do not change anything from here.

image-168

Click Next

Click Next. Again, simply click Next.

image-170

Click Next

Make sure to add the checkmark (✔) on all of the boxes. Then click on Next.

image-171

Check all of the boxes, and click Next

Click on Install.

image-172

Click Install

It might take a little time to finish the installation.

image-173

Let it finish…

Click on Finish.

image-175

Click Finish

Congrats — you’ve successfully installed VS Code/VS Code Insiders on your system. Now, cheers! 🥂

How to Prepare VS Code/VS Code Insiders For C and C++ Code

First, open VS Code or VS Code Insiders.

Go to the Extension tab. Search for «C» or «C++» and install the first one that is already verified by Microsoft itself.

image-178

Install C/C++ extension

Also, install C/C++ Extension Pack. It should also be verified by Microsoft.

image-179

Install C/C++ Extension Pack

Then you have to search for Code Runner and install the extension as well.

image-180

Install Code Runner Extension

Now, we need to change some settings.

image-177

Change some settings

Click the gear box (It is called the Manage section), and then click Settings. Alternatively, you can also use the shortcut keys Ctrl + ,. You need to replace the Ctrl key with the Command key for Mac.

image-182

Type «Run code in terminal» and press Enter key

In the search bar, type «Run code in terminal» and press the Enter key.

Scroll down a little bit until you find Code-runner: Run In Terminal. Make sure that the box is checked (✔).

image-184

Make sure to check the box

Now you need to restart your VS Code/VS Code Insiders. Simply close and reopen the program.

How to Test Your Code

Simply open VS Code/VS Code Insiders, open any folder, and create any file with the extension .c for the C file and .cpp for the C++ file.

After writing your code, you can run the code directly using the play button you’ll find in the upper right corner.

image-185

This is how you can run any C/C++ program from VS Code/Insiders

It will compile and then run the code directly. After running a code, the code runner button would be set default to run directly. So, your computer is 100% ready for compiling and running any C/C++ programming code.  😀

Conclusion

Thanks for reading the entire article. If it helps you then you can also check out other articles of mine at freeCodeCamp.

If you want to get in touch with me, then you can do so using Twitter, LinkedIn, and GitHub.

You can also SUBSCRIBE to my YouTube channel (Code With FahimFBA) if you want to learn various kinds of programming languages with a lot of practical examples regularly.

If you want to check out my highlights, then you can do so at my Polywork timeline.

You can also visit my website to learn more about me and what I’m working on.

Thanks a bunch!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

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. When you create a *.cpp file, the extension adds features such as syntax highlighting (colorization), smart completions and hovers (IntelliSense), and error checking.

C++ language features

Install the extension

  1. Open VS Code.
  2. Select the Extensions view icon on the Activity bar or use the keyboard shortcut (⇧⌘X (Windows, Linux Ctrl+Shift+X)).
  3. Search for 'C++'.
  4. Select Install.

C/C++ extension

Set up your C++ Environment

C++ is a compiled language meaning your program’s source code must be translated (compiled) before it can be run on your computer. The C/C++ extension doesn’t include a C++ compiler or debugger, since VS Code as an editor relies on command-line tools for the development workflow. You need to install these tools or use the tools already installed on your computer.

Check if you have a compiler installed

Note: 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).

Common compilers that already come preinstalled on some platforms are the GNU Compiler Collection (GCC) on Linux and the Clang tools with Xcode on macOS.

To check if you already have them installed:

  1. Open a new VS Code terminal window using (⌃⇧` (Windows, Linux Ctrl+Shift+`))

  2. Use the following command to check for the GCC compiler g++:

    g++ --version
    

    Or this command for the Clang compiler clang:

    clang --version
    

The output should show you the compiler version and details. If neither are found, 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. Otherwise, use the instructions in the section below to install a compiler.

Install a compiler

If you don’t have a compiler installed, you can follow one of our installation tutorials:

Windows:

Go to the MSVC tutorial

Go to the MinGW tutorial

Linux:

Go to the GCC tutorial

macOS:

Go to the Clang tutorial

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.

Example: Install MinGW-x64 on Windows

To understand the process, let’s install Mingw-w64 via MSYS2. Mingw-w64 is a popular, free toolset on Windows. It provides up-to-date native builds of GCC, Mingw-w64, and other helpful C++ tools and libraries.

  1. Download using this direct link to the MinGW installer.

  2. Run the installer and follow the steps of the installation wizard. Note, MSYS2 requires 64 bit Windows 8.1 or newer.

  3. In the wizard, choose your desired Installation Folder. Record this directory for later. In most cases, the recommended directory is acceptable. The same applies when you get to setting the start menu shortcuts step. When complete, ensure the Run MSYS2 now box is checked and select Finish. A MSYS2 terminal window will then automatically open.

  4. In this terminal, install the MinGW-w64 toolchain by running the following command:

    pacman -S --needed base-devel mingw-w64-ucrt-x86_64-toolchain
    
  5. Accept the default number of packages in the toolchain group by pressing Enter.

    MYSS2 Installer

  6. Enter Y when prompted whether to proceed with the installation.

  7. Add the path to your MinGW-w64 bin folder to the Windows PATH environment variable by using the following steps:

    1. In the Windows search bar, type Settings to open your Windows Settings.
    2. Search for Edit environment variables for your account.
    3. In your User variables, select the Path variable and then select Edit.
    4. Select New and add the MinGW-w64 destination folder you recorded during the installation process to the list. If you selected the default installation steps, the path is: C:\msys64\ucrt64\bin.
    5. Select OK to save the updated PATH. For the new PATH to be available, reopen your console windows.
  8. Check that your MinGW-w64 tools are correctly installed and available, open a new Command Prompt and type:

gcc --version
g++ --version
gdb --version

You should see output that states which versions of GCC, g++ and GDB you have installed. If this is not the case, make sure your PATH entry matches the Mingw-w64 binary location where the compiler tools are located or reference the troubleshooting section.

Create a Hello World App

To make sure the compiler is installed and configured correctly, lets create a Hello World C++ program.

Create a C++ file

  1. On Windows, launch a Windows command prompt (Enter Windows command prompt in the Windows search bar). On macOS and Linux, you can enter these commands in the terminal.
  2. Run the following commands. They are creating an empty folder called projects where you can place all your VS Code projects. The next commands create and navigate you to a subfolder called helloworld. From there, you are opening helloworld directly in VS Code using the code command.
mkdir projects
cd projects
mkdir helloworld
cd helloworld
code .

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.

File Explorer New File button

Add Hello World source code

Paste in the following source code:

#include <iostream>

int main()
{
    std::cout << "Hello World" << std::endl;
}

Now press ⌘S (Windows, Linux Ctrl+S) to save the file. You can also enable AutoSave to automatically save your file changes, by checking Auto Save in the main File menu.

Run helloworld.cpp

  1. Make sure you have helloworld.cpp open so it is the active file in your editor.

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

    Screenshot of helloworld.cpp and play button

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

    C++ debug configuration dropdown

You are only prompted to choose a compiler the first time you run helloworld.cpp. This compiler becomes «default» compiler set in your tasks.json file.

  1. After the build succeeds, you should see «Hello World» appear in the integrated Terminal.

    screenshot of program output

Congratulations! You’ve just run your first C++ program in VS Code! The next step is to learn more about the Microsoft C/C++ extension’s language features such as IntelliSense, code navigation, build configuration, and debugging using one of the Tutorials in the next section.

Tutorials

Get started with C++ and VS Code with tutorials for your environment:

  • GCC on Windows via MinGW
  • Microsoft C++ on Windows
  • GCC on Linux
  • GCC on Windows Subsystem For Linux
  • Clang/LLVM on macOS
  • CMake Tools on Linux

Documentation

You can find more documentation on using the Microsoft C/C++ extension under the C++ section of the VS Code website, where you can find articles on:

  • Debugging
  • Editing
  • Settings
  • FAQ

C++ TOC on code.visualstudio.com

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:

  1. Install the VS Code Remote Development Extension Pack.
  2. If the remote source files are hosted in WSL, use the WSL extension.
  3. If you are connecting to a remote machine with SSH, use the Remote — SSH extension.
  4. 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 extension in the VS Code Marketplace

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, you can take this quick survey.

7/24/2023

Уважаемый usernameusername,

примерно год назад я точно так же не мог с первого раза настроить VS Code.

Как справедливо указали в комментариях — есть прекрасная официальная документация по настройке. Тем не менее, я оставлю свой ответ, так как он более детальный в некоторых моментах. А в других моментах — менее детальный :-)

Чтобы настроить VSC, хорошо бы научиться компилировать и запускать Вашу программу из командной строки. А потом настройки, котрые для этого понадобились, добавить в правильные места в файлах конфигурации VS code.

Труднность этого процесса именно в «зоопарке» разных возможностей. На этого не стоит пугаться.

Кроме того, настройка немного отличатся для разных систем (Linux, windows, macos), а Вы не указали, какая система у вас.

Я приведу пример настройки для компилятора gcc под Win64. Можно повторить мои шаги, а когда получится — сделать самостотельную настройку, например, на другой компилятор.

  1. Устанавливаем msys2. Я установил его в C:\Programs\msys64. При этом сам msys2 позаботился о том, чтобы путь к его директории C:\Programs\msys64\mingw64\bin оказался в path. Проверить это можно, выполнив в консоли команду path

  2. Устанавливаем компилятор и дебаггер. Я делаю это с помощью пакета msys2, выполнив в окне, котрое открывает msys2, следующие команды:

     pacman -Syuu
    

    Эта команда обновляет msys2. Она может закрыть консоль — это нормально, нужно перезапустить ее и ввести ту же команду, чтобы завершить обновление. Хорошей идеей будет время от времени обновляться, чтобы всегда иметь последнюю версию компилятора.

    Затем:

     pacman -S mingw-w64-x86_64-gcc
     pacman -S mingw-w64-x86_64-gdb
    

Теперь в Вашей системе есть компилятор и дебаггер. Проверить это просто: открываем новое окно консоли, пишем g++ --version

Если ответом не является версия — надо поискать, что пошло не так. Проверить path, возможно, отредактировать его вручную.

Такую же проверку хорошо бы сделат для дебаггера: gdb --version

  1. Пишем hello world. Это позволит нам окончательно убедиться, что компилятор работает. в любой директории созадем файл hello.cpp с текстом

     #include <iostream>
     int main() {
         std::cout << "Hello world!" << std::endl;
         return 0;
     };
    

потом в этой папке в командной строке компилируем командой g++ hello.cpp -o hello.exe
Если появился файл hello.exe, и он запускается и вывоит строчку — ок, этот шаг завершен.

  1. А вот теперь можно поставить VSC. Обратите внимание, что редакций есть несколько, во первых для 32 и 64 битных систем, а во вторых — то, что назывется «User Installer» и «System Installer». Выбираем 64 битный System Installer на странице загрузки

  2. В VSC ставим расширение для работы с C++, оно называется C/C++ for Visual Studio Code и написано Microsoft

  3. Теперь запустим VSC в папке Вашего проекта. Пусть это будет папка C:\Projects\. Делается это так: запускам консоль. Переходим в консоли в папку (cd C:\Projects\). Запускаем VSC командой code ..

Важно то, что при этом создаётся папка настроек VSC, котрые находятся по пути C:\Projects\.vscode. В этой папке нужно создать 4 файла, я приведу их в минимальном варианте. Пути — для моей системы, где msys2 установлен в C:\Programs\msys64\.

Файл tasks.json — отвечает за то, чтобы работала комбинация клавиш Ctrl+shift+B для сборки программы:

    {
        "version": "2.0.0",
        "tasks": [
            {
                "type": "shell",
                "label": "g++.exe build active file",
                "command": "C:/Programs/msys64/mingw64/bin/g++.exe",
                "args": [
                    "-std=c++17",
                    "-g",
                    "${file}",
                    "-o",
                    "${fileDirname}\\${fileBasenameNoExtension}.exe"
                ],
                "options": {
                    "cwd": "C:\\Programs\\msys64\\mingw64\\bin"
                },
                "problemMatcher": [
                    "$gcc"
                ],
                "group": {
                    "kind": "build",
                    "isDefault": true
                }

            }
        ]
    }

Файл launch.json — отвечает за работу дебаггера:

    {
        "version": "0.2.0",
        "configurations": [
            {
                "name": "g++.exe build and debug active file",
                "type": "cppdbg",
                "request": "launch",
                "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
                "args": [],
                "stopAtEntry": false,
                "cwd": "${workspaceFolder}",
                "environment": [],
                "externalConsole": false,
                "MIMode": "gdb",
                "miDebuggerPath": "C:\\Programs\\msys64\\mingw64\\bin\\gdb.exe",
                "setupCommands": [
                    {
                        "description": "Enable pretty-printing for gdb",
                        "text": "-enable-pretty-printing",
                        "ignoreFailures": true
                    }
                ],
                "preLaunchTask": "g++.exe build active file",
                "internalConsoleOptions": "neverOpen"
            }
        ]
    }

Файл settings.json — как то отвечает за файловые ассоциации, возможно даже, что он не особо нужен. Но лишним не будет:

    {
        "files.associations": {
            "ostream": "cpp",
            "iostream": "cpp",
            "iomanip": "cpp",
            "chrono": "cpp",
            "iosfwd": "cpp",
            "thread": "cpp",
            "array": "cpp",
            "string_view": "cpp",
            "initializer_list": "cpp",
            "utility": "cpp",
            "valarray": "cpp",
            "optional": "cpp",
            "sstream": "cpp"
        }
    }

Файл c_cpp_properties.json — отвечает за расположение include — файлов:

    {
        "configurations": [
            {
                "name": "Win32",
                "includePath": [
                    "${workspaceFolder}/**", 
                    "C:/Programs/msys64/mingw64/include/**"
                ],
                "defines": [
                    "_DEBUG",
                    "UNICODE",
                    "_UNICODE"
                ],
                "windowsSdkVersion": "8.1",
                "compilerPath": "C:\\Programs\\msys64\\mingw64\\bin\\g++.exe",
                "cStandard": "c11",
                "cppStandard": "c++17",
                "intelliSenseMode": "gcc-x86"
            }
        ],
        "version": 4
    }

Если Вы создадите эти файлы, а потом заново запустите в этой директории VSC — то всё уже должно работать. То есть, программы на C++ будут компилироваться, запускаться в отладке (по F5) и показывать значения переменных в окне отладчика.

Теперь — самое важное. Как только заработает — Вам нужно эту папку .vscode копировать к корень каждой папки с проектом на C++. Это позволит VSC запускаться с Вашими настройками.

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

Успехов!

PS. Время от времени попадаются полезные дополнительные возможности для настройки.

Вот такой фрагмент файла tasks.json позволяет очищать окно терминала перед каждым билдом — полезно, чтобы уже не видеть уже исправленных ошибок, оставшихся от предыдущей попытки сборки (Источник):

    "presentation": {
            "clear": true                        // <-- this line
      }

  • Как работать на клавиатуре без мышки на компьютере windows 7
  • Как работать с ventoy для windows
  • Как работать с autoruns для windows 10
  • Как работать с unix на windows
  • Как работать с aircrack ng windows