Ubuntu系统使用vscode写C++的方法,ubuntuvscode
Ubuntu系统使用vscode写C++的方法,ubuntuvscode
visual studio code 本质上是个编辑器,并不是IDE,因此需要自己配编译器。不过vscode会推荐一些官方插件,还是比较方便的。
vscode 需要改写 .vscode/launch.json 和 .vscode/tasks.json,前者描述调试工程环境,如何启动任务,后者定义编译方法
工程示例
假定一个简单工程
/* solution.h */ class Solution { public: void Say(); }; /* solution.cpp */ #include#include "solution.h" void Solution::Say(){ std::cout << "HI!" << std::endl; } /* main.cpp */ #include "solution.h" int main () { Solution sln; sln.Say(); return 0; }
launch.json
用vscode打开一个工程文件夹,然后 查看->调试(ctrl+shift+d)选择编译环境
选择好后会自动生成一个launch.json文件,修改“program”和“preLaunchTask”即可
{ // 使用 IntelliSense 了解相关属性。 // 悬停以查看现有属性的描述。 // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "(gdb) Launch", "type": "cppdbg", "request": "launch", "program": "${workspaceFolder}/hello", // 修改输出程序路径 "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": true, "preLaunchTask": "build_hello", // 添加 "preLaunchTask" 编译任务 "MIMode": "gdb", "setupCommands": [ { "description": "Enable pretty-printing for gdb", "text": "-enable-pretty-printing", "ignoreFailures": true } ] } ] }
项目 | 说明 |
---|---|
name | 配置名称,会在启动配置的下拉菜单中显示 |
type | 配置类型,只能为cppdbg |
request | 请求类型,可以为launch或attach |
program | 将要调试的程序的路径 |
args | 调试时传递给程序的命令行参数 |
stopAtEntry | 设为true程序会暂停在入口处 |
cwd | 调试程序时的工作目录 |
environment | 环境变量 |
externalConsole | 调试时是否显示控制台窗口 |
MIMode | 指定连接的调试器,可以为gdb或lldb |
preLaunchTask | 调试开始前执行的任务,一般为编译程序 |
tasks.json
ctrl+shift+p 搜索选择 “配置任务”
修改生成的 tasks.json为
{ // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "tasks": [ { "label": "build_hello", // 与launch的"preLaunchTask"一致 "type": "shell", "command": "make", // 使用 makefile "problemMatcher": { "owner": "cpp", "fileLocation": [ "relative", "$workspaceRoot" ], "pattern": { "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$", "file": 1, "line": 2, "column": 3, "severity": 4, "message": 5 } }, "group": { "kind": "build", "isDefault": true } } ] }
“type” 可以选 shell 或 process
如果是 shell ,那么 “command” 的内容会被解释成一条shell命令,否则会被理解为执行一个程序 官方使用更为灵活的 shell + sh 的方式
“type”=shell,”command”=”xx.sh”,在sh文件里实现复杂的编译方法 这里我使用了 shell + make 的方式
工程目录下再写一个标准的 makefile
/* makefile */ hello : main.o solution.o g++ -o hello main.o solution.o main.o : main.cpp solution.h g++ -g -c main.cpp solution.o : solution.h solution.cpp g++ -g -c solution.cpp clean : rm main.o solution.o hello
编译和调试
完成 tasks.json 后 ctrl+shift+b 编译 代码插入断点,F5开始调试,F11单步(makefile 的输出和launch.json的“program”要一致
评论暂时关闭