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.omain.o : main.cpp solution.h g++ -g -c main.cppsolution.o : solution.h solution.cpp g++ -g -c solution.cppclean : rm main.o solution.o hello
編譯和調試
完成 tasks.json 後 ctrl+shift+b 編譯 代碼插入斷點,F5開始調試,F11單步(makefile 的輸出和launch.json的“program”要一致