原文鏈接: vscode源文件和可執行文件分離
前言
用vscode寫c/c++時, 為了方便, 會把不同的源文件放在一個文件夾里
這里不是做項目, 一個源文件就是一個單獨的程序
然后生成的可執行文件和源代碼就會放在一個目錄里, 還是同名, 就很容易點錯, 所以就想着改改
環境和版本
- Visual Studio Code 1.54.3
- Liunx Ubuntu 18.04 LTS
- g++ 7.5.0
code-runner設置
打開vscode, 菜單欄文件
->首選項
->設置

使用搜索功能, 搜索code-runner
並找到Excutor Map
, 點擊在settings.json
編輯
出來這樣的頁面, 我們要修改的是cpp
這一行, 當然, 其它語言也是一樣
修改成如下:
"cpp": "cd $dir && if [ ! -d \"bin\" ];then mkdir bin;fi && g++ $fileName -o bin/$fileNameWithoutExt && bin/$fileNameWithoutExt"
其中if [ ! -d \"bin\" ];then mkdir bin;fi
為判斷bin
是否存在, 如果不存在則創建, 當然, bin
這個名字也改成自己喜歡的
調試
配置調試的是launch.json
這個文件, 而在調試程序執行前會需要先進行編譯生成可執行二進制文件, 這時就需要配置task.json
文件
在launch.json
中, 通過改寫preLaunchTask
參數, 並在task.json
中添加參數, 可以達到預先創建bin
文件夾的目的
task.json
中加上如下任務:
{
"type":"shell",
"label":"創建bin文件夾",
"command":" if [ ! -d \"bin\" ];then mkdir bin;fi"
}
並在生成可執行文件的參數中, 更改目錄
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/bin/${fileBasenameNoExtension}"
],
launch.json
中修改可執行文件的位置
"program": "bin/${fileBasenameNoExtension}"
lauch.json
中添加任務:
"preLaunchTask": [
"創建bin文件夾",
"C/C++: g++ 生成活動文件"
]
完整tasks.json
參考代碼
{
"tasks": [
{
"type":"shell",
"label":"創建bin文件夾",
"command":" if [ ! -d \"bin\" ];then mkdir bin;fi"
},
{
"type": "cppbuild",
"label": "C/C++: g++ 生成活動文件",
"command": "/usr/bin/g++",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/bin/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "調試器生成的任務。"
}
],
"version": "2.0.0"
}
完整的launch.json
{
// 使用 IntelliSense 了解相關屬性。
// 懸停以查看現有屬性的描述。
// 欲了解更多信息,請訪問: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "g++ - 生成和調試活動文件",
"type": "cppdbg",
"request": "launch",
"program": "bin/${fileBasenameNoExtension}",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "為 gdb 啟用整齊打印",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": [
"創建bin文件夾",
"C/C++: g++ 生成活動文件"
],
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
沒必要直接復制粘貼, 版本可能會更改而不適用, 看懂怎么改的即可
windows系統方法也類似, 要注意的
-
路徑分隔符號不一樣, linux是
/
, windows是\
-
創建文件夾的命令需要修改, 這里給出參考
if not exist bin ( md bin);