Movatterモバイル変換


[0]ホーム

URL:


TryMCP servers to extend agent mode in VS Code!

Dismiss this update

Configure VS Code for Microsoft C++

In this tutorial, you configure Visual Studio Code to use the Microsoft Visual C++ compiler and debugger on Windows.

After configuring VS Code, you will compile and debug a simple Hello World program in VS Code. This tutorial does not teach you details about the Microsoft C++ toolset or the C++ language. For those subjects, there are many good resources available on the Web.

If you have any problems, feel free to file an issue for this tutorial in theVS Code documentation repository.

Prerequisites

To successfully complete this tutorial, you must do the following:

  1. InstallVisual Studio Code.

  2. Install theC/C++ extension for VS Code. You can install the C/C++ extension by searching for 'c++' in the Extensions view (⇧⌘X (Windows, LinuxCtrl+Shift+X)).

    C/C++ extension

  3. Install the Microsoft Visual C++ (MSVC) compiler toolset.

    If you have a recent version of Visual Studio, open the Visual Studio Installer from the Windows Start menu and verify that the C++ workload is checked. If it's not installed, then check the box and select theModify button in the installer.

    You can also install theDesktop development with C++ workload without a full Visual Studio IDE installation. From the Visual StudioDownloads page, scroll down until you seeTools for Visual Studio under theAll Downloads section and select the download forBuild Tools for Visual Studio 2022.

    Build Tools for Visual Studio download

    This will launch the Visual Studio Installer, which will bring up a dialog showing the available Visual Studio Build Tools workloads. Check theDesktop development with C++ workload and selectInstall.

    Cpp build tools workload

Note: You can use the C++ toolset from Visual Studio Build Tools along with Visual Studio Code to develop, build, and test any C++ code as long as you also have a valid Visual Studio license (either Community, Pro, or Enterprise).

Check your Microsoft Visual C++ installation

To use MSVC from a command line or VS Code, you must run from aDeveloper Command Prompt for Visual Studio. An ordinary shell such as PowerShell, Bash, or the Windows command prompt does not have the necessary path environment variables set.

To open the Developer Command Prompt for VS, start typing 'developer' in the Windows Start menu, and you should see it appear in the list of suggestions. The exact name depends on which version of Visual Studio or the Visual Studio Build Tools you have installed. Select the item to open the prompt.

Developer Command Prompt

You can test that you have the C++ compiler,cl.exe, installed correctly by typing 'cl' and you should see a copyright message with the version and basic usage description.

Checking cl.exe installation

If the Developer Command Prompt is using the BuildTools location as the starting directory (you wouldn't want to put projects there), navigate to your user folder (C:\users\{your username}\) before you start creating new projects.

Note: If for some reason you can't run VS Code from aDeveloper Command Prompt, you can find a workaround for building C++ projects with VS Code inRun VS Code outside a Developer Command Prompt.

Create Hello World

From the Developer Command Prompt, create an empty folder called "projects" where you can store all your VS Code projects, then create a subfolder called "helloworld", navigate into it, and open VS Code (code) in that folder (.) by entering the following commands:

mkdir projectscd projectsmkdir helloworldcd helloworldcode .

The "code ." command opens VS Code in the current working folder, which becomes your "workspace". As you go through the tutorial, you will see three files created in a.vscode folder in the workspace:

  • tasks.json (build instructions)
  • launch.json (debugger settings)
  • c_cpp_properties.json (compiler path and IntelliSense settings)

Add a source code file

In the File Explorer title bar, select theNew File button and name the filehelloworld.cpp.

New File title bar button

Add hello world source code

Now paste in this source code:

#include <iostream>#include <vector>#include <string>using namespace std;int main(){    vector<string> msg {"Hello","C++","World","from","VS Code","and the C++ extension!"};    for (const string& word : msg)    {        cout << word <<" ";    }    cout << endl;}

Now press⌘S (Windows, LinuxCtrl+S) to save the file. Notice how the file you just added appears in theFile Explorer view (⇧⌘E (Windows, LinuxCtrl+Shift+E)) in the side bar of VS Code:

File Explorer

You can also enableAuto Save to automatically save your file changes, by checkingAuto Save in the mainFile menu.

The Activity Bar on the far left lets you open different views such asSearch,Source Control, andRun. You'll look at theRun view later in this tutorial. You can find out more about the other views in the VS CodeUser Interface documentation.

Note: When you save or open a C++ file, you may see a notification from the C/C++ extension about the availability of an Insiders version, which lets you test new features and fixes. You can ignore this notification by selecting theX (Clear Notification).

Explore IntelliSense

In your newhelloworld.cpp file, hover overvector orstring to see type information. After the declaration of themsg variable, start typingmsg. as you would when calling a member function. You should immediately see a completion list that shows all the member functions, and a window that shows the type information for themsg object:

Statement completion IntelliSense

You can press theTab key to insert the selected member; then, when you add the opening parenthesis, you will see information about any arguments that the function requires.

Run helloworld.cpp

Remember, the C++ extension uses the C++ compiler you have installed on your machine to build your program. Make sure you have a C++ compiler installed before attempting to run and debughelloworld.cpp in VS Code.

  1. Openhelloworld.cpp so that it is the active file.

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

    Screenshot of helloworld.cpp and play button

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

    C++ debug configuration dropdown

You'll only be asked to choose a compiler the first time you runhelloworld.cpp. This compiler will be set as the "default" compiler intasks.json file.

  1. After the build succeeds, your program's output will appear in the integratedTerminal.

    screenshot of program output

If you get an error trying to build and debug with cl.exe, make sure you havestarted VS Code from the Developer Command Prompt for Visual Studio using thecode . shortcut.

Error notification when trying to use MSVC without running VS Code from the Developer Command Prompt for VS

The first time you run your program, the C++ extension createstasks.json, which you'll find in your project's.vscode folder.tasks.json stores build configurations.

Your newtasks.json file should look similar to the JSON below:

{  "version":"2.0.0",  "tasks": [    {      "type":"shell",      "label":"C/C++: cl.exe build active file",      "command":"cl.exe",      "args": [        "/Zi",        "/EHsc",        "/Fe:",        "${fileDirname}\\${fileBasenameNoExtension}.exe",        "${file}"      ],      "problemMatcher": ["$msCompile"],      "group": {        "kind":"build",        "isDefault":true      },      "detail":"Task generated by Debugger."    }  ]}

Note: You can learn more abouttasks.json variables in thevariables reference.

Thecommand setting specifies the program to run; in this case that is "cl.exe". Theargs array specifies the command-line arguments that will be passed to cl.exe. These arguments must be specified in the order expected by the compiler.

This task tells the C++ compiler to take the active file (${file}), compile it, and create an executable file (/Fe: switch) in the current directory (${fileDirname}) with the same name as the active file but with the.exe extension (${fileBasenameNoExtension}.exe), resulting inhelloworld.exe for our example.

Thelabel value is what you will see in the tasks list; you can name this whatever you like.

Thedetail value is what you will as the description of the task in the tasks list. It's highly recommended to rename this value to differentiate it from similar tasks.

TheproblemMatcher value selects the output parser to use for finding errors and warnings in the compiler output. For cl.exe, you'll get the best results if you use the$msCompile problem matcher.

From now on, the play button will read fromtasks.json to figure out how to build and run your program. You can define multiple build tasks intasks.json, and whichever task is marked as the default will be used by the play button. In case you need to change the default compiler, you can runTasks: Configure default build task. Alternatively you can modify thetasks.json file and remove the default by replacing this segment:

    "group": {        "kind":"build",        "isDefault":true    },

with this:

    "group":"build",

Modifying tasks.json

You can modify yourtasks.json to build multiple C++ files by using an argument like"${workspaceFolder}/*.cpp" instead of"${file}".This will build all.cpp files in your current folder. You can also modify the output filename by replacing"${fileDirname}\\${fileBasenameNoExtension}.exe" with a hard-coded filename (for example"${workspaceFolder}\\myProgram.exe").

Debug helloworld.cpp

To debug your code,

  1. Go back tohelloworld.cpp so that it is the active file.
  2. Set a breakpoint by clicking on the editor margin or using F9 on the current line.screenshot of breakpoint in helloworld.cpp
  3. From the drop-down next to the play button, selectDebug C/C++ File.Screenshot of play button drop-down
  4. ChooseC/C++: cl.exe build and debug active file from the list of detected compilers on your system (you'll only be asked to choose a compiler the first time you run or debughelloworld.cpp).C++ debug configuration dropdown

The play button has two modes:Run C/C++ File andDebug C/C++ File. It will default to the last-used mode. If you see the debug icon in the play button, you can select the play button to debug, instead of selecting the drop-down menu item.

If you get an error trying to build and debug with cl.exe, make sure you havestarted VS Code from the Developer Command Prompt for Visual Studio using thecode . shortcut.

Error notification when trying to use MSVC without running VS Code from the Developer Command Prompt for VS

Explore the debugger

Before you start stepping through the code, let's take a moment to notice several changes in the user interface:

  • The Integrated Terminal appears at the bottom of the source code editor. In theDebug Output tab, you see output that indicates the debugger is up and running.

  • The editor highlights the line where you set a breakpoint before starting the debugger:

    Initial breakpoint

  • TheRun and Debug view on the left shows debugging information. You'll see an example later in the tutorial.

  • At the top of the code editor, a debugging control panel appears. You can move this around the screen by grabbing the dots on the left side.

    Debugging controls

Step through the code

Now you're ready to start stepping through the code.

  1. Click or press theStep over icon in the debugging control panel.

    Step over button

    This will advance program execution to the first line of the for loop, and skip over all the internal function calls within thevector andstring classes that are invoked when themsg variable is created and initialized. Notice the change in theVariables window on the left.

    Debugging windows

    In this case, the errors are expected because, although the variable names for the loop are now visible to the debugger, the statement has not executed yet, so there is nothing to read at this point. The contents ofmsg are visible, however, because that statement has completed.

  2. PressStep over again to advance to the next statement in this program (skipping over all the internal code that is executed to initialize the loop). Now, theVariables window shows information about the loop variables.

  3. PressStep over again to execute thecout statement. (Note that the C++ extension does not print any output to theDebug Console until the loop exits.)

  4. If you like, you can keep pressingStep over until all the words in the vector have been printed to the console. But if you are curious, try pressing theStep Into button to step through source code in the C++ standard library!

    Breakpoint in gcc standard library header

    To return to your own code, one way is to keep pressingStep over. Another way is to set a breakpoint in your code by switching to thehelloworld.cpp tab in the code editor, putting the insertion point somewhere on thecout statement inside the loop, and pressingF9. A red dot appears in the gutter on the left to indicate that a breakpoint has been set on this line.

    Breakpoint in main

    Then pressF5 to start execution from the current line in the standard library header. Execution will break oncout. If you like, you can pressF9 again to toggle off the breakpoint.

Set a watch

Sometimes you might want to keep track of the value of a variable as your program executes. You can do this by setting awatch on the variable.

  1. Place the insertion point inside the loop. In theWatch window, select the plus sign and in the text box, typeword, which is the name of the loop variable. Now view the Watch window as you step through the loop.

    Watch window

  2. Add another watch by adding this statement before the loop:int i = 0;. Then, inside the loop, add this statement:++i;. Now add a watch fori as you did in the previous step.

  3. To quickly view the value of any variable while execution is paused on a breakpoint, you can hover over it with the mouse pointer.

    Mouse hover

Customize debugging with launch.json

When you debug with the play button orF5, the C++ extension creates a dynamic debug configuration on the fly.

There are cases where you'd want to customize your debug configuration, such as specifying arguments to pass to the program at runtime. You can define custom debug configurations in alaunch.json file.

To createlaunch.json, chooseAdd Debug Configuration from the play button drop-down menu.

Add debug configuration play button menu

You'll then see a dropdown for various predefined debugging configurations. ChooseC/C++: cl.exe build and debug active file.

C++ debug configuration dropdown

VS Code creates alaunch.json file, which looks something like this:

{  "version":"0.2.0",  "configurations": [    {      "name":"C/C++: cl.exe build and debug active file",      "type":"cppvsdbg",      "request":"launch",      "program":"${fileDirname}\\${fileBasenameNoExtension}.exe",      "args": [],      "stopAtEntry":false,      "cwd":"${workspaceFolder}",      "environment": [],      "externalConsole":false,      "preLaunchTask":"C/C++: cl.exe build active file"    }  ]}

In the JSON above,program specifies the program you want to debug. Here it is set to the active file folder (${fileDirname}) and active filename with the.exe extension (${fileBasenameNoExtension}.exe), which ifhelloworld.cpp is the active file will behelloworld.exe. Theargs property is an array of arguments to pass to the program at runtime.

By default, the C++ extension won't add any breakpoints to your source code and thestopAtEntry value is set tofalse.

Change thestopAtEntry value totrue to cause the debugger to stop on themain method when you start debugging.

From now on, the play button andF5 will read from yourlaunch.json file when launching your program for debugging.

C/C++ configurations

If you want more control over the C/C++ extension, you can create ac_cpp_properties.json file, which will allow you to change settings such as the path to the compiler, include paths, C++ standard (default is C++17), and more.

You can view the C/C++ configuration UI by running the commandC/C++: Edit Configurations (UI) from the Command Palette (⇧⌘P (Windows, LinuxCtrl+Shift+P)).

Command Palette

This opens theC/C++ Configurations page. When you make changes here, VS Code writes them to a file calledc_cpp_properties.json in the.vscode folder.

Command Palette

Visual Studio Code places these settings in.vscode\c_cpp_properties.json. If you open that file directly, it should look something like this:

{  "configurations": [    {      "name":"Win32",      "includePath": ["${workspaceFolder}/**"],      "defines": ["_DEBUG","UNICODE","_UNICODE"],      "windowsSdkVersion":"10.0.18362.0",      "compilerPath":"C:/Program Files (x86)/Microsoft Visual Studio/2019/BuildTools/VC/Tools/MSVC/14.24.28314/bin/Hostx64/x64/cl.exe",      "cStandard":"c11",      "cppStandard":"c++17",      "intelliSenseMode":"msvc-x64"    }  ],  "version":4}

You only need to add to theInclude path array setting if your program includes header files that are not in your workspace or in the standard library path.

Compiler path

ThecompilerPath setting is an important setting in your configuration. The extension uses it to infer the path to the C++ standard library header files. When the extension knows where to find those files, it can provide useful features like smart completions andGo to Definition navigation.

The C/C++ extension attempts to populatecompilerPath with the default compiler location based on what it finds on your system. The extension looks in several common compiler locations.

ThecompilerPath search order is:

  • First check for the Microsoft Visual C++ compilerOpe
  • Then look for g++ on Windows Subsystem for Linux (WSL)
  • Then g++ for Mingw-w64.

If you have g++ or WSL installed, you might need to changecompilerPath to match the preferred compiler for your project. For Microsoft C++, the path should look something like this, depending on which specific version you have installed: "C:/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools/VC/Tools/MSVC/14.16.27023/bin/Hostx64/x64/cl.exe".

Reusing your C++ configuration

VS Code is now configured to use the Microsoft C++ compiler. The configuration applies to the current workspace. To reuse the configuration, just copy the JSON files to a.vscode folder in a new project folder (workspace) and change the names of the source file(s) and executable as needed.

Run VS Code outside the Developer Command Prompt

In certain circumstances, it isn't possible to run VS Code fromDeveloper Command Prompt for Visual Studio (for example, in Remote Development through SSH scenarios). In that case, you can automate initialization ofDeveloper Command Prompt for Visual Studio during the build using the followingtasks.json configuration:

{  "version":"2.0.0",  "windows": {    "options": {      "shell": {        "executable":"cmd.exe",        "args": [          "/C",          // The path to VsDevCmd.bat depends on the version of Visual Studio you have installed.          "\"C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/Common7/Tools/VsDevCmd.bat\"",          "&&"        ]      }    }  },  "tasks": [    {      "type":"shell",      "label":"cl.exe build active file",      "command":"cl.exe",      "args": [        "/Zi",        "/EHsc",        "/Fe:",        "${fileDirname}\\${fileBasenameNoExtension}.exe",        "${file}"      ],      "problemMatcher": ["$msCompile"],      "group": {        "kind":"build",        "isDefault":true      }    }  ]}

Note: The path toVsDevCmd.bat might be different depending on the Visual Studio version or installation path. You can find the path toVsDevCmd.bat by opening a Command Prompt and runningdir "\VsDevCmd*" /s.

Troubleshooting

The term 'cl.exe' is not recognized

If you see the error "The term 'cl.exe' is not recognized as the name of a cmdlet, function, script file, or operable program.", this usually means you are running VS Code outside of aDeveloper Command Prompt for Visual Studio and VS Code doesn't know the path to thecl.exe compiler.

VS Code must either be started from the Developer Command Prompt for Visual Studio, or the task must be configured torun outside a Developer Command Prompt.

You can always check that you are running VS Code in the context of the Developer Command Prompt by opening a new Terminal (⌃⇧` (Windows, LinuxCtrl+Shift+`)) and typing 'cl' to verifycl.exe is available to VS Code.

fatal error C1034: assert.h: no include path set

In this case,cl.exe is available to VS Code through thePATH environment variable, but VS Code still needs to either be started from theDeveloper Command Prompt for Visual Studio, or be configured torun outside the Developer Command Prompt. Otherwise,cl.exe does not have access to important environment variables such asINCLUDE.

Next steps

3/7/2023

[8]ページ先頭

©2009-2025 Movatter.jp