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

猜你喜欢

转载自blog.csdn.net/zhaoyin214/article/details/106788006