赞
踩
在C++项目的开发过程当中,对编写的代码做调试可以使用gdb等工具,但gdb命令使用起来有一定学习成本,对于简单的debug流程,使用可视化编辑器打断点等方式可极大程度提高调试效率,并且入门门槛比较低。该文章从C++项目的编译流程开始介绍如何基于vscode配置debug环境。
vscode是微软推出的可视化编辑器,其有较强的插件接入扩展功能,通过插件为各类语言提供了较好的编辑和调试环境。
.安装vscode编辑器
.安装C/C++插件
vscode提供了tasks.json和launch.json作为用户和编辑器的交互入口,其中tasks.json文件中定义了项目工程的编译和构建配置信息,launch.json中定义了项目工程的debugger配置信息。简单理解就是,tasks.json为编译阶段的配置文件,launch.json为运行阶段的配置文件。详情可参考在linux环境使用vscode。
创建一个demo工程,目录为/home/wanggang/code/test,包括三个文件main.cpp,test.cpp,test.h。其中test.cpp和test.h这两个文件生成libtest.so动态库被main.cpp函数所调用。
main.cpp文件
#include <iostream> #include <string> #include <vector> #include "test.h" using namespace std; int main() { vector<string> data = {"hello", "world", "very", "nice"}; for (auto it : data) { cout << it << endl; } printNum(); return 0; }
test.h文件
#ifndef TEST_H
#define TEST_H
using namespace std;
int printNum(void);
int printStr(void);
#endif
test.c文件
#include <iostream>
#include <string>
#include <vector>
#include "test.h"
using namespace std;
int printNum(void) {
cout << "pring num" << endl;
}
int printStr(void) {
cout << "pring str" << endl;
}
使用如下命令编译出libtest.so动态库(自测)
g++ -shared -fPIC test.cpp -o libtest.so
使用如下指令编译出可执行文件(自测)
g++ main.cpp -L./ -ltest -o main
tasks.json文件配置
在.vscode目录下创建tasks.json文件,其中如果需要直接使用该文件,主要更改args和cwd选项就可。
{ "tasks": [ { "type": "cppbuild", "label": "C/C++: g++ build active file", "command": "/usr/bin/g++", // 指定编译器 "args": [ // args为g++/gcc命令后面跟的参数 "-fdiagnostics-color=always", "-g", // -g选项为开启gdb调试所需要的选项 "/home/wanggang/code/test/main.cpp", "-L/home/wanggang/code/test", "-ltest", // 链接共享库 "-o", "/home/wanggang/code/test/main", // 指定生成二进制文件名,需要在launch.json文件中指定该文件为可执行文件 ], "options": { "cwd": "/home/wanggang/code/test/" // 指定工作目录 }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "Task generated by Debugger." } ], "version": "2.0.0" }
点击Run and Debug,可以看到tasks.json中的配置已生效并且编译成功
配置launch.json文件,其中主要更改program和cwd变量,其它变量按需修改
{ "version": "0.2.0", "configurations": [ { "name": "C/C++: g++ build and debug active file", "type": "cppdbg", "request": "launch", "program": "/home/wanggang/code/test/main", // 指定运行的可执行文件,和tasks.json中保持一致 "args": [], // 可执行文件如果需要跟参数在其中配置 "stopAtEntry": false, "cwd": "/home/wanggang/code/test", // 工作目录 "environment": [{ "name": "LD_LIBRARY_PATH", "value": "$LD_LIBRARY_PATH:/home/wanggang/code/test" }], // 配置环境变量 "externalConsole": false, "MIMode": "gdb", // 指定调试参数 "miDebuggerPath": "/usr/bin/gdb", "setupCommands": [ { "description": "Enable pretty-printing for gdb", "text": "-enable-pretty-printing", "ignoreFailures": true } ], "preLaunchTask": "C/C++: g++ build active file" } ] }
运行debug,可以看到如下截图,debug运行环境配置成功
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。