Linux環境下,使用VSCode編譯C++工程

Linux環境下,使用VS Code編譯C++工程

1. 準備

sudo apt-get install g++

或者更新

sudo apt-get update
  • 安裝gdb調試器
sudo apt-get install build-essential gdb

2. 創建Hello World

VS Code需要爲工程配置3個文件:

`tasks.json` :編譯器配置

`launch.json`:調試器配置

`c_cpp_properties.json` (編譯器路徑、智能提示)
  • 創建Hello World工程
mkdir hello_world
cd hello_world
code .
  • 新建hello_world.cpp
#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;
}

在這裏插入圖片描述

3. 編譯hello_world.cpp

.vscode文件夾中,創建tasks.json文件,選擇C/C++: g++ build active file

在這裏插入圖片描述

{
  "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
      }
    }
  ]
}

command:指定運行程序(g++);

args:指定g++的命令行參數,參數必須按照編譯器指定的順序。
本例中,g++編譯活動文件(${file},若要編譯所有文件,可用${workspaceFolder}/*.cpp"替換),並在當前目錄(${fileDirname})中創建與活動文件同名(無擴展名)的可執行文件(${fileBasenameNoExtension});

label:任務列表中的值,可以任意命名。

isDefaultgroup對象成員,true表示按Ctrl + Shift + B時,該任務執行;如果設爲false,可以從Terminal菜單Tasks: Run Build Task處執行。

在這裏插入圖片描述
在這裏插入圖片描述

4. 調試hello_world.cpp

.vscode文件夾中,創建launch.json文件,選擇g++ build and debug active file

在這裏插入圖片描述

{
  "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"
    }
  ]
}

program:指定要調試的程序,${fileDirname}表示活動文件文件夾、${fileBasenameNoExtension}表示不帶擴展名的活動文件名。

默認情況下,C++ extension不會在源代碼中添加斷點,並將stopAtEntry設爲false。將stopAtEntry更改爲true,以便調試時,調試器在main方法上停止。

5. C/C++配置

若要修改C/C++ extension,可創建c_cpp_properties.json文件,該文件用於設置編譯器路徑、C++標準(默認爲C++17)等。調用命令面板(Ctrl+Shift+P),選擇C/C++: Edit Configurations (UI)

在這裏插入圖片描述

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

參考

Using C++ on Linux in VS Code

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章