Movatterモバイル変換


[0]ホーム

URL:


Tryagent mode in VS Code!

Dismiss this update

Using C++ on Linux in VS Code

In this tutorial, you will configure Visual Studio Code to use the GCC C++ compiler (g++) and GDB debugger on Linux. GCC stands for GNU Compiler Collection; GDB is the GNU debugger.

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

If you have trouble, 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++ 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

Ensure GCC is installed

Although you'll use VS Code to edit your source code, you'll compile the source code on Linux using the g++ compiler. You'll also use GDB to debug. These tools are not installed by default on Ubuntu, so you have to install them. Fortunately, that's easy.

First, check to see whether GCC is already installed. To verify whether it is, open a Terminal window and enter the following command:

gcc -v

If GCC isn't installed, run the following command from the terminal window to update the Ubuntu package lists. An out-of-date Linux distribution can sometimes interfere with attempts to install new packages.

sudo apt-get update

Next install the GNU compiler tools and the GDB debugger with this command:

sudo apt-get install build-essential gdb

Create Hello World

From the terminal window, create an empty folder calledprojects to store your VS Code projects. Then create a subfolder calledhelloworld, navigate into it, and open VS Code in that folder by entering the following commands:

mkdir projectscd projectsmkdir helloworldcd helloworldcode .

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

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

Add hello world source code file

In the File Explorer title bar, selectNew File and name the filehelloworld.cpp.

New File title bar button

Paste in the following 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;    return 0;}

Now press⌘S (Windows, LinuxCtrl+S) to save the file. Notice that your files are listed 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 edge of Visual Studio Code 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 thehelloworld.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'll see information about 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. Chooseg++ 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

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++: g++ build active file",      "command":"/usr/bin/g++",      "args": ["-g","${file}","-o","${fileDirname}/${fileBasenameNoExtension}"],      "options": {        "cwd":"/usr/bin"      },      "problemMatcher": ["$gcc"],      "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 g++.Theargs array specifies the command-line arguments that will be passed to g++. These arguments must be specified in the order expected by the compiler.

This task tells g++ to take the active file (${file}), compile it, and create an executable file in the current directory (${fileDirname}) with the same name as the active file but without an extension (${fileBasenameNoExtension}), resulting inhelloworld 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 see as the description of the task in the tasks list. It's highly recommended to rename this value to differentiate it from similar tasks.

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}" with a hard-coded filename (for example 'helloworld.out').

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++: g++ 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 just select the play button to debug, instead of selecting the drop-down menu item.

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 line 12, which is a breakpoint that you set 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

If you already have a launch.json file in your workspace, the play button will read from it when figuring out how run and debug your C++ file. If you don’t have launch.json, the play button will create a temporary “quick debug” configuration on the fly, eliminating the need for launch.json altogether!

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 side.

    Debugging windows

  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 last cout executes.)

  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.

    When the loop has completed, you can see the output in theDebug Console tab of the integrated terminal, along with some other diagnostic information that is output by GDB.

    Debug console display

Set a watch

To keep track of the value of a variable as your program executes, set awatch on the variable.

  1. Place the insertion point inside the loop. In theWatch window, click 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. 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

Next, you'll create atasks.json file to tell VS Code how to build (compile) the program. This task will invoke the g++ compiler to create an executable file from the source code.

It's important to havehelloworld.cpp open in the editor because the next step uses the active file in the editor for context to create the build task in the next step.

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. Chooseg++ 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++: g++ build and debug active file",      "type":"cppdbg",      "request":"launch",      "program":"${fileDirname}/${fileBasenameNoExtension}",      "args": [],      "stopAtEntry":false,      "cwd":"${workspaceFolder}",      "environment": [],      "externalConsole":false,      "MIMode":"gdb",      "miDebuggerPath":"/usr/bin/gdb",      "setupCommands": [        {          "description":"Enable pretty-printing for gdb",          "text":"-enable-pretty-printing",          "ignoreFailures":true        }      ],      "preLaunchTask":"C/C++: g++ 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 without an extension${fileBasenameNoExtension}, which ifhelloworld.cpp is the active file will behelloworld. 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.

IntelliSense configuration window

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

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":"Linux",      "includePath": ["${workspaceFolder}/**"],      "defines": [],      "compilerPath":"/usr/bin/gcc",      "cStandard":"c11",      "cppStandard":"c++17",      "intelliSenseMode":"clang-x64"    }  ],  "version":4}

Reusing your C++ configuration

VS Code is now configured to use gcc on Linux. 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.

Troubleshooting

Compiler and linking errors

The most common cause of errors (such asundefined _main, orattempting to link with file built for unknown-unsupported file format, and so on) occurs whenhelloworld.cpp is not the active file when you start a build or start debugging. This is because the compiler is trying to compile something that isn't source code, like yourlaunch.json,tasks.json, orc_cpp_properties.json file.

Next steps

5/13/2022

[8]ページ先頭

©2009-2025 Movatter.jp