您现在的位置是:首页 >技术教程 >Ubuntu中使用vscode+cmake进行编译调试网站首页技术教程

Ubuntu中使用vscode+cmake进行编译调试

河北一帆 2023-06-01 04:00:02
简介Ubuntu中使用vscode+cmake进行编译调试

首先新建一个文件夹作为工作空间

mkdir test

进入工作空间文件夹,在vscode中打开

cd test
code .

创建一个c++文件

#include<iostream>
 
using namespace std;
 
int main(){
 
    int a = 2+3;
    int b = a+3;
 
    for(int i = 0; i<10; i++){
        cout<<"hello vs code & cmake..."<<endl;
    }
    
    return 0;
}

因为要使用cmake编译,所以要创建CMakeLists.txt,加入如下代码

cmake_minimum_required(VERSION 2.6)
 
project(vscode_cmake)

add_executable (vscode_cmake ./main.cc)

再创建build.sh文件

vim build.sh

写入以下内容

mkdir build
cd build
cmake .. -DCMAKE_BUILD_TYPE=Debug
make

注意给build.sh文件赋予权限,否则可能无法运行

chmod +x build.sh && ./build.sh

此时,工作空间文件夹下包含三个文件,main.cc  CMakeLists.txt  build.sh

在vscode中按ctrl+shift+p,选择Configure Tasks回车,再选择Create tasks,json file from template回车,再选择others,写入如下内容

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "vscode_cmake",
            "type": "shell",
            "command": "./build.sh",
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

ctrl+shift+p,Run Build Tasks,即完成了编译,tasks.json文件就是运行了command里写的build.sh。而build.sh文件就是使用cmake进行了编译,这里注意编译的type要写debug,不要写release,否则后面打不了断点。

ctrl+shift+d, create a launch.json file,debugger选择GDB,删除默认生成的"configurations",点击右下角Add Configuration,修改“program”为cmake编译生成的executable文件的路径,注意要写绝对路径

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "(gdb) Launch",
            "type": "cppdbg",
            "request": "launch",
            "program": "/home/username/test/build/vscode_cmake",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                },
                {
                    "description": "Set Disassembly Flavor to Intel",
                    "text": "-gdb-set disassembly-flavor intel",
                    "ignoreFailures": true
                }
            ]
        }
    ]
}

在main.cc文件夹中打上断点,就可以调试了。

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。