linux c程序 makefile,Linux+VSCode+makefile调试C程序

本文记录了我之前在 Ubuntu 系统使用 VSCode + makefile 来调试 C 程序的过程。

如果不习惯在 Linux 使用命令行 gdb 调试 C/C++ 程序,可以尝试此方法,利用 VSCode 的调试界面调试。

VSCode 调试运行项目一共有两个步骤,“构建”+“运行”,对应 "tasks.json" 和 "launch.json" 这两个配置文件。

1. 其中 "tasks.json" 是用来构建项目的

{

// See https://go.microsoft.com/fwlink/?LinkId=733558

// for the documentation about the tasks.json format

"version": "2.0.0",

"tasks": [

{

"label": "shell", // The task's user interface label

"type": "shell", // Defines whether the task is run as a process or as a command inside a shell.

"command": "make" // The command to be executed. Can be an external program or a shell command.

"args": [ // Arguments passed to the command when this task is invoked.

]

}

]

}

目前我的 "tasks.json" 是这样的,注意其中的 "label" 和 "command" 这两个配置选项。

"label" 是指该任务的标签,在 "launch.json" 里使用。

"command" 就是指在构建项目时使用的命令,默认的配置是 gcc,注意该选项的提示,

可以是一个外部程序或者一个 Shell 命令。

这句话有什么用呢?一般使用 VSCode 构建简单项目,只需要简单在 "args" 里加上 gcc 编译时需要的参数即可,如果项目涉及四五个文件同时编译,这个时候再手动增改 "args" 就很麻烦,也不利于修改。如果我们写好编译项目的 makefile 文件,VSCode 编译的时候执行 make 命令即可,后续增删编译文件有 makefile 语法,方便修改。

相应的,如果使用 cmake 构建项目,则 ”command" 可以是一个 Shell 脚本文件,用于使用 cmake 构建。

2. "launch.json" 用来配置调试相关选项

{

// 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": "${workspaceFolder}/shell", // Full path to program executable.

"args": [], // Command line arguments passed to the program.

"stopAtEntry": true, // Optional parameter. If true, the debugger should stop at the entrypoint of the target.

// If processId is passed, has no effect.

"cwd": "${workspaceFolder}",

"environment": [],

"externalConsole": false,

"MIMode": "gdb",

"setupCommands": [

{

"description": "Enable pretty-printing for gdb",

"text": "-enable-pretty-printing",

"ignoreFailures": true

}

],

"preLaunchTask": "shell" // Task to run before debug session starts.

}

]

}

利用 VSCode 生成模板 "launch.json" 文件,我们只需要修改少数几个选项即可。

"program",该选项的值是可执行文件的绝对路径,可以使用 VSCode 里的一些变量来简化,此处是当前工作文件夹下的 shell 程序。

"args",这是传递给可执行文件的参数。

"stopAtEntry",该命令为 true 表明调试程序时,会在 main.c 的第一行代码停住。

"preLaunchTask",在调试开始之前运行的项目,需要与 "tasks.json" 里的 "label" 的选项值一致。

安装上述配置完成后,就可以按 F5 进行调试了。

若有问题,欢迎在下方留言,一起讨论。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值