task.json 和 launch.json 是 vscode中两个最为关键的文件配置。
一、task.json
可见官网:https://code.visualstudio.com/docs/editor/tasks#vscode
cmd+shift+p 打开搜索栏,搜 “task”创建,同时会生成 .vscode 目录。
一个简单的C++配置
等于在终端执行:g++ -std=c++11 -stdlib=libc++ -g file.cpp -o file
{
"version": "2.0.0",
"tasks": [
{
"type": "shell", // 表明任务执行的是 shell命令
"label": "testMake", // 任务名字
"command": "g++", // 执行的命令
"args": [
"-std=c++11",
"-stdlib=libc++",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": ["$gcc"], // 使用gcc捕获错误
"group": {
"kind": "build",
"isDefault": true
// 任务分组,因为是tasks而不是task,意味着可以连着执行很多任务
// 在build组的任务们,可以通过在Command Palette(F1) 输入run build task来运行
// 当然,如果任务分组是test,你就可以用run test task来运行
}
}
]
}
二、launch.json
debug配置
{
// 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": "g++ Build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/output",
"args": [],
"stopAtEntry": true, // 选为true则会在打开控制台后停滞,暂时不执行程序
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false, // 是否使用外部控制台,选false的话,我的vscode会出现错误
"MIMode": "lldb",
"preLaunchTask": "testMake"
//在launch之前运行的任务名,这个名字一定要跟tasks.json中的任务名字大小写一致
}
]
}
三、Makefile支持
task.json 配置如下,launch.json 同上。
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "testMake",
"command":"make",
"args":[
"output"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": ["$gcc"],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
四、基本的变量
https://code.visualstudio.com/docs/editor/variables-reference
假设打开文件是:/home/user/project/folder/test.cpp,文件夹:/home/user/project
- ${workspaceFolder} :VsCode打开的文件夹路径,即:/home/user/project
- ${workspaceFolderBasename}:VsCode打开的文件名字,没有路径。即:project
- ${file} :现在打开的文件,即:/home/user/project/folder/test.cpp
- ${fileWorkspaceFolder} :打开文件所在工作空间文件夹,即:/home/user/project/
- ${relativeFile} : 相对空间目录的路径,即:folder/test.cpp
- ${relativeFileDirname} :folder
- ${fileBasename} :test.cpp
- ${fileBasenameNoExtension} : test
- ${fileDirname} :/home/user/project/folder
- ${fileExtname} : .cpp
- ${cwd} - the task runner’s current working directory on startup
- ${lineNumber} - the current selected line number in the active file
- ${selectedText} - the current selected text in the active file
- ${execPath} - the path to the running VS Code executable
- ${defaultBuildTask} - the name of the default build task
- ${pathSeparator} - the character used by the operating system to separate components in file paths
参考
1、https://zhuanlan.zhihu.com/p/92175757
2、https://code.visualstudio.com/docs/cpp/config-clang-mac若有收获,就点个赞吧