[Translation] official website documents, ubuntu use vscode debugging c ++

Visual Studio Code official website document https://code.visualstudio.com/docs/cpp/config-wsl
official website there are documents compiled Python, Java documentation, including the win, linux, macos, written very popular, it is recommended to see, flag : Guo Siji I can not read the screen upside down to eat.
Freehand text translation, translation is a rival who's literal translation, the use of multiple translation translation.
Many may be less than the content of the document, a summary at the end, do not want to see the translation of last roll please see the configuration items and instructions.

Net official document translation

On the WSL write C ++ with VS code

In this tutorial, you will be in Windows Subsystem for Linux configuration on the VS code (WSL) Ubuntu system to use such as GCC and GDB debugging tools. GCC representatives GNU Compiler Collection; GDB is the GNU debugger. WSL is a Linux subsystem on the Windows system that runs directly on the real machine, rather than a virtual machine.

Note: You can use most of the tutorial VS code directly in C ++ on Linux devices do related work.

VS code used in the WSL directly support Remote-WSL expansion work. We recommend the use of WSL development model , as well as all the source files by the compiler Linux distribution management. For more information see VS Remote Code Development .

After the wizard is complete, you will have the ability to create and configure your C ++ project, and can explore VS code documentation for more information about its characteristics. This guide will not teach you GCC, Linux or C ++ language, resources on these issues can get a lot from the Internet.

If you have any questions, please rest assured that in the VS Code documentation repository question tutorial for this purpose.

Prerequisites

In order to successfully complete this wizard, you must do several tasks below:

  1. Installation VS code
  2. Installation Remote - WSL extension
  3. Install Windows the Subsystem for Linux , and then install the Linux distribution of your choice on the page links. This tutorial uses Ubuntu. Be sure to remember your password when you install Linux users, because it is required when installing other software.

Set up your Linux environment

  1. Bash terminal WSL is open. If you install an Ubuntu release, then click on it in the results list in the Windows search bar search "Ubuntu". For the Debian distribution, search for "Debian" the same.

The terminal will display a command prompt, the default user name of your computer name and composition, and the next you as to the user's home directory. On Ubuntu looks like this:

  1. Create a directory projects, then create a subdirectory helloworld:
mkdir projects
cd projects
mkdir helloworld
  1. You will edit the source code in Linux systems use VS code, will use g ++ compiler to compile the code. At the same time, you will be debugging Linux using GDB. These tools are not installed by default in Ubuntu, so you have to install them yourself. Fortunately, this work is very simple!

  2. In the WSL command prompt, run apt-get updateto update the list of packages Ubuntu. Outdated versions can sometimes interfere with the installation of new packages.

sudo apt-get update

You can also execute sudo apt-get update && sudo apt-get dist-upgradeinstructions to download the latest version of the system package, but that's because of the constraints of the network connection speed and spend more time.

  1. Install the GNU compiler tool and GDB debugging tools at the command line, the command is as follows:
sudo apt-get install build-essential gdb
  1. By positioning g ++ and gdb to verify the installation was successful. If the file name is not in whereisthe return command, try to run the update command again.
whereis g++
whereis gdb

Note: The installation steps g ++ compiler and GDB debugger instead of WSL conducted on a Linux device. You have to run VS code, as well as edit, compile and debug your helloworld project.

VS code to run in the WSL

Switch terminal WSL's helloworld to your project directory, code .open the VS code:

cd $HOME/projects/helloworld
code .

You will see a message "Install VScode Server" is. Then VS code is to download and install a small server to the Linux side, VS code on the desktop and it will establish contact. VS code will then start and open the helloworlddirectory. File Manager is displayed in the title bar ** [WSL: Ubuntu] **, is being run on behalf of VS code WSL.

You can also see a remote environment in the status bar

If you click on the remote status bar, you'll see a list of remote commands sessions. For example, you want to end the session on the WSL, you can choose from the list closed distal connection command. WSL execution command prompt code .command to restart VS code.

code. command opens the VS code in the current directory, which is your "workspace." As the tutorial, you will see the working directory .vscodecreates three files in the directory:

  • c_cpp_properties.json(Build path and intelligent configuration)
  • tasks.json(Compilation instructions)
  • launch.json(Debug settings)

Add the source code file

Select the file manager on the title bar new file button to create a helloworld.cppfile.

Installation C / C ++ extensions

After creating the file, VS code will recognize that it is a C ++ language files, if you have not installed in the Microsoft C / C ++ Extension , it will prompt you to install it.

Extended window displaying an operation button, choose to install, and then reload the complete C / C ++ extensions installation.

If you are already VS code locally installed extensions C / C ++ language, you have to expand the window in the extended ( Ctrl+ the Shift + the X-) in those extensions are installed in the WSL. Select mounted to WSL button and reload the local installation of the extension will be attached to WSL.

Add helloworld source code

Paste this 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;
}

Press Ctrl+Sto save the file. VS code in the sidebar file management window ( Ctrl+Shift+E), the file you just pay attention to is how to add display.

You can also turn on auto-save function, automatically save changes to a file, the file Click on the main menu are saved automatically .

You can open the activity in the left-most column of different windows, such as search , source code management and operation . In the back of this tutorial you will see the run window. You can VS code the user interface documentation to find more information about the other windows.

Smart Tips

In the new helloworld.cppdocument, to hover vector, or stringon the type of information you can see. Statement msgafter variables you want to call it is necessary to member functions msg.begin with. Then you will see a complete list of all member functions display, next to a window msgtype information object.

You can press the Tabinsert member function selected key; later, when writing on the left parenthesis, you will see all the information about the function arguments.

Compile helloworld.cpp

Next, you want to create a tasks.jsonfile that tells how VS code compiler. This work will create a source of executable files by means of WSL g ++ compiler.

In the main menu bar terminal > configuration tasks generated by default , a drop-down list, showing a variety of predefined C ++ compiler. Select G ++ Build the Active File , this option will create a display immediately in the editor.

This step will .vscodecreate a directory in the tasks.jsonfile, and open it in the editor.

The newly created tasks.jsonfile should look like JSON format, such as the following:

{
  "version": "2.0.0",
  "tasks": [
    {
      "type": "shell",
      "label": "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
      }
    }
  ]
}

commandOptions indicate which program you want to run, g ++ when this case. argsTo pass an array indicating g ++ command-line parameters, these parameters must comply with the order of the compiler requirements. This work is to call the g ++ compiler target file ( ${file}), and (in the current directory ${fileDirname}) does not create a file suffix, files with the same name as the target executable file, the example in this tutorial to create a helloworldfile.

Note: You can refer to variables learn more about the tasks.jsoncontents of the variable.

labelValue of the option will be displayed in the task list, you can modify it willful.

groupObject "isDefault":truerepresents the contents press Ctrl+Shift+Bthe shortcut key to work. This configuration is for convenience only; if you set it to false, you can still end with a menu to run the generated task to run.

The compiler is run

  1. Return helloworld.cpp. You will compile helloworld.cpp.

  2. Press Ctrl+Shift+Bor terminal selection from the main menu to run the task generating runs defined in tasks.jsonthe compilation task file.

  3. When the task starts, source code editing box will appear below the terminal panel. After compilation, the terminal will output the relevant information is compiled successfully. Compile success looks like this:

  1. Click the + button to create a new terminal, the terminal runs in WSL environment to helloworlddirectory files to a working directory. Execute lscommand to see an executable file helloworld(no file extension).

  1. In the terminal input ./helloworldoperation helloworld.

Modify tasks.json

You can tasks.jsonbe more than compiled C ++ files, such as using ".cpp"substitute ${file}. You may also be ${fileDirname}/${fileBasenameNoExtension}replaced by a fixed name to modify the output file name (such as "helloworld.out" change).

Debugging helloworld.cpp

Next, you want to create a launch.jsonfile to configure VS code, press it in your F5call when GDB debugger. In the main menu operation > Add Configuration ... select C ++ (the GDB / a LLDB) .

A list of predefined display various debug configuration. Select G ++ Build and Debug the Active File .

VS code to create a launch.jsonfile and open it in the editor, then compile and run "helloworld".

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

programOption specifies the program to be debugged. Here set the target directory ${fileDirname}target file name and extension without ${fileBasenameNoExtion}a corresponding helloworld.cppobject files generated helloworld.

Here default, C ++ source code extensions do not add any breakpoint stopAtEntryvalue false. The stopAtEntryset truewill stop at when you start debugging mainfunction of position.

Optional contact the rest of the steps that can help you familiar with editing and debugging.

Begin a debugging session

  1. Return helloworld.cpp, which is currently the target file.

  2. Press F5or the main menu, select Run > Start Debugging . Before stepping through, we take a minute to look at the user interface changes:

  • Code editing terminal box appears below. In the Debug Console tab, you can see the output of the debugger starts running.
  • Editor maindisplays the first line of the highlighted function. This is the default for the C ++ you set breakpoints:

  • Run the left side of the window display debugging information. Later in this guide are examples.
  • Appears in the top of the editor to debug a control panel. You can grab a few points on the left side to move it.

Step through the code

Now you're ready to start stepping through code.

  1. Click on the debug control panel Step over the chart.

This will make the program execution to the first line of the loop, and create and initialize msgskipped variables vectorand stringall functions inside the class. Note change in the variable on the left side of the window.

In this case, it should be a problem, although variable names for loop is visible, but not to perform, so this step can not read the contents. msgVariables can be seen, because that statement has been completed.

  1. Press again Step over the program to execute a statement to the next (skipping internal code for all initialization cycle). Now, variable window will show variable information loop.

  2. Then Step over execution to the coutstatement. (Note that in VS code 2019 released March's, C ++ extensions in the debug console will not output any information before the end of the cycle.)

  3. You can always press the Step over until all the words vectors are printed out. If you Step Into very curious button, you can click on it to give it a try, it will jump to the internal standard C ++ library code!

To return to your code, a method is to keep pressing the Step over ; another way is to switch to the helloworld.cppmiddle, in a program loop coutat the statement by F9adding a breakpoint. A red dot appears in the left margin position indicates that the breakpoint has been added to this line.

Then press F5started in the standard library, the program will stop at the coutposition statement. Press again to F9cancel the breakpoint.

After the end of the cycle, the console can see the output in the debug information, as well as other debugging information of GDB.

Set Monitor

Sometimes, you might want to track the value of variables during program execution. You can set the monitor to achieve this function as a variable.

  1. Focusing the cursor in the cycle, the monitoring window and click to add expression loop input variable word. Next, looking at the monitor window when debugging.

  1. Plus before the loop int i = 0;statement, adding in a loop ++istatements above step to add imonitoring variables.

  2. When the breakpoint is, if you want to quickly see the value of any variable, you can hover over it.

C / C ++ configuration

If you want to C / C ++ extensions for more control, you can create a c_cpp_properties.jsonfile, where you can configure many settings, such as compiler path, the path contains the header files and C ++ standard (default C ++ 17), and so on.

You can command panel ( Ctrl+Shift+P) run ** C / C ++: Open C / C ++ user interface configuration Edit Configurations (UI) ** command.

This opens the C / C ++ configuration page. When you make changes therein, VS code modification will write the contents of .vscodea directory of c_cpp_properties.jsonfiles.

If the header file of your program no longer works header file directory or the standard library, you only modify the Include path is enough.

VS code uses these settings into .vscode/c_cpp_properties.jsona file, if the direct open it, it looks like this:

{
  "configurations": [
    {
      "name": "Linux",
      "includePath": ["${workspaceFolder}/**"],
      "defines": [],
      "compilerPath": "/usr/bin/gcc",
      "cStandard": "c11",
      "cppStandard": "c++17",
      "intelliSenseMode": "clang-x64"
    }
  ],
  "version": 4
}

WSL closed session

When you have finished working on the WSL, you can master file (menu and command panel Ctrl+Shift+P) to perform close a remote connection command to exit the session. This restarts the VS code running locally. You can file > Open Recent list , select the band ** [WSL] ** suffix file, reopen WSL session.

Other steps

  • Explore VS code user navigation .
  • Recalling the C ++ extensions overview .
  • Plus create a new workspace, copy the files to your .json, need to adjust the settings, program name, etc. for the new workspace, and then began to knock the code!

Configuration summary

Open a directory as a workspace, creates two files tasks.json and launch.json in .vscode directory settings. You can manually create directories and files directly, without setting in the VS code.

  • Create a tasks.jsonfile for compilation. The menu bar Select Terminal> configuration tasks generated by default, a drop-down list, showing a variety of predefined C ++ compiler. Select g ++ build active file. Refer to the following:
{
    "version": "2.0.0",
    "tasks": [
      {
        "type": "shell",
        "label": "g++ go!go!go!",
        "command": "/usr/bin/g++",
        "args": [
          "-g",
          "${file}",
          "-o",
          "${fileDirname}/${fileBasenameNoExtension}"
        ],
        "options": {
          "cwd": "/usr/bin"
        },
        "problemMatcher": [
          "$gcc"
        ],
        "group": {
          "kind": "build",
          "isDefault": true
        }
      }
    ]
  }

command specified in g ++. g ++ array args parameter. The current file directory ${fileDirname}. No file suffix, with the same name as the source file executable files ${fileBasenameNoExtension}. label easily change.
isDefault: true representatives of press Ctrl + Shift + B shortcut to work. Details, refer to the Variables Reference .

  • Create a launch.jsonfile, for running the debugger. The main menu, select Run (Debug)> Add Configuration ... then select C ++ (GDB / LLDB). Option g ++ build and debug active file. launch.json Reference:
{
    // 使用 IntelliSense 了解相关属性。 
    // 悬停以查看现有属性的描述。
    // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "come on!",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "为 gdb 启用整齐打印",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ]
        }
    ]
}

program option specifies the program to be debugged.

After which you can compile, debug. Before commissioning remember to compile the source file.

Guess you like

Origin www.cnblogs.com/foxer-z/p/12520904.html