linux+vsCode+makefile – 调试C
总流程
利用makefile文件,使用make命令,进行多C文件编译,生成可调试程序,利用vsCode调试功能进行调试
一、make使用
引用:http://blog.youkuaiyun.com/feixiaoxing/article/details/7197095
首先编写add.c文件,
#include "test.h"
#include <stdio.h>
int add(int a, int b)
{
return a + b;
}
int main()
{
printf(" 2 + 3 = %d\n", add(2, 3));
printf(" 2 - 3 = %d\n", sub(2, 3));
return 1;
}
再编写sub.c文件
#include "test.h"
int sub(int a, int b)
{
return a - b;
}
最后编写test.h文件
#ifndef _TEST_H
#define _TEST_H
int add(int a, int b);
int sub(int a, int b);
#endif
编写makefile
test:add.o sub.o
gcc -g -o test add.o sub.o
add.o: add.c test.h
gcc -g -c add.c
sub.o:sub.c test.h
gcc -g -c sub.c
clean:
rm -rf test
rm -rf *.o
注: clean下的代码,需使用make clean才可调用
-g -c -o意义:
- -g:为调试使用
- -c:仅编译(Compile),不连接(Make)
- -o:输出文件名
二、vsCode调试配置
- tasks.json文件编写(用于生成可调试程序,如直接在终端上使用make,即不用编写)
{
"version": "2.0.0",
"tasks": [
{
"taskName": "shell", // 任务名称,与launch.json的preLaunchTask相对应
"command": "make", // 在shell中使用命令,如需加参数,可再添加args属性
"type":"shell"
}
]
}
- launch.json文件编写(用于调用调试程序)
{
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",// 配置名称,将会在启动配置的下拉菜单中显示
"type": "cppdbg",// 配置类型,这里只能为cppdbg
"request": "launch",// 请求配置类型,可以为launch(启动)或attach(附加)
"program": "${workspaceRoot}/test",// 将要进行调试的程序的路径
"stopAtEntry": true, // 设为true时程序将暂停在程序入口处,我一般设置为true
"cwd": "${workspaceRoot}",// 调试程序时的工作目录
"environment": [],// (环境变量?)
"externalConsole": true,// 调试时是否显示控制台窗口,一般设置为true显示控制台
"MIMode": "gdb",// 指定连接的调试器,可以为gdb或lldb。
"preLaunchTask": "shell" // 调试会话开始前执行的任务,一般为编译程序。与tasks.json的taskName相对应,可根据需求选择是否使用
}
]
}
调试
在左侧添加断点后,即可进行调试