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

Narottam04

Narottam04

Posted on

• Updated on



 



 



 



 



 

Why should you use visual studio code ?

Visual Studio Code is a free source-code editor made by Microsoft for Windows, Linux and macOS. Features include support for debugging, syntax highlighting, intelligent code completion, snippets, code refactoring, and embedded Git.

It currently supports hundreds of programming languages and file formats. Several common languages come supported by default (JavaScript, HTML, CSS, etc), and others gain support by adding integrated extensions. If you find a language that isn’t supported by an existing extension, the open nature of the extensions system means you can build one.

In this blog post you will learn how to set up visual studio code on your local environment for C and C++, this can get tricky but if you follow step by step you can set it up easily.

Step 1: Download Visual studio code.

Type vscode on your browser and click on the first link of the page, or just click here.

install vscode

vscode

Now download the installer according to your operating system.

Step 2: Install vscode

This step is easy, accept the agreement and click next.

install

Check the following options as shown in above image and click next and install.

Step 3: Download extensions for visual studio code.

vscode editor

Once you have installed visual studio code, now its time to install some extensions. Click on the button where red arrow is pointing in above image.

Now click on C/C++ extension from Microsoft as shown in the below image. If you don’t see the extension search C/C++ and you will find it.

extension

Install the extension.

c

Now we have to install another extension called Code Runner.

code runner

Now we have successfully installed code editor but we need a compiler to compile and output our code, for that we will be installing MinGW.

Step 4: Download MinGW

Type mingw on google and choose following first link as shown in the image below or Click Here.

mingw

Now click download.

download

Step 5: Install MinGW

Open the installer, you should see something like the below image. Click on install and choose your directory where the software should be installed and click continue.

mingw

mingw install

After installing, click on continue and right click on every checkbox and choose mark for installation.

install

After checking all checkboxes you should see something like image below.

install

Now click Installation on top left corner and then choose Apply Changes. You should see something like shown in the image below.

install

And then click on Apply.

Once you complete the installation, you should see something like the image below.

install

Click close and close the installer.

Step 6: Copy Bin Path

Now open ‘This PC’ and open ‘local Disk C’ you should see mingw file and click on bin folder.

bin path

Now you have to copy the folder destination which is above the page as shown below.

bin path

Now right click and copy or just press ‘Ctrl + C’ on your keyboard.

Step 7: Environment Variables

Open ‘Control Panel’ from your start menu and click on System. If you don’t find system on your control panel just type ‘system’ on the search bar which you can find in top right corner of the control panel.

variable

Click on Advanced system setting on right side you should see system properties as shown in the image below.

variable

Now click on Environment Variables you should see something as shown in the image below.

variable

Now click on the path in system variable and click on edit as shown in the image below.

variable

Now click on new and paste the bin path that we have copied in the previous step and then click Ok.

variable

Now click ok till there are no pop ups left.

Step 8: Let’s check if MinGW has been successfully installed or not.

Click on search button near the bottom left of windows and search for command prompt.

cmd

g++ --version

Enter fullscreen mode

Exit fullscreen mode

cmd

And if you see something like the image above, voila! we did it.

🛑 🛑 If you get some error don’t worry just reinstall mingw as shown in the step 4 and step 5 and it should solve the problem.🛑🛑

Step 8: Let’s write our first program in C++

Hurray! we have successfully set up vscode for C and C++ now lets test it by writing our first program in vscode.

Open vscode.

Click on ‘File’ in upper left section and choose ‘Open Folder’.

Lets make a new folder in dekstop and select the folder.

vscode

Now click on the document symbol in the side bar. If you dont see a sidebar just press Ctrl + B on keyboard.

Now make a file with a extension of .cpp as shown in the image below

vscode

Now lets type our first code. You can copy and paste the code that I have provided below.

hello world

#include<iostream>
using namespace std;
int main()
{
    cout<<"hello world";
}

Enter fullscreen mode

Exit fullscreen mode

Step 9: Run the code.

Right click and click on run or press keyboard shortcut ‘Ctrl+Alt+N’.

terminal

And there you go you have written your first program in C++, I hope this tutorial was helpful if you are facing any problem while installing let me know in the comment section or email me at blog.webdrip.in.

Get more insights like this on my blog, https://blog.webdrip.in.

  • Visual c для visual studio 2022 x64 скачать windows 10
  • Visual studio 2017 for windows 7
  • Visual c для visual studio 2017 x64 скачать windows 10
  • Visual studio 2017 community скачать для windows 7
  • Visual c для visual studio 2015 x32 скачать windows 10