最近在學習linux webserver開發,需要在linux下調試自己的C/C++代碼,但是linux下不像在windows下,直接Visio Studio或者其它集成開發環境那么方便,現在的linux下開發,比較麻煩。于是可以考慮使用VScode遠程開發。但是網上的很多教程都不是很清晰,這里在嘗試了很多教程后,踩了不少坑,最后總結如下。【推薦學習:《VScode》】
1.系統配置
遠程系統:ubuntu18.04(虛擬機)
開發主機:windows10
2.ubuntu遠程端安裝軟件和設置
(1)安裝必要軟件:ssh(系統通信),gdb,gsdbserver(代碼調試):
sudo apt-get install openssh-server sudo apt-get install gdb sudo apt-get install gdbserver
(2)創建測試文件夾和文件
立即學習“C++免費學習筆記(深入)”;
注意:
- 雖然你可能想一步到位,直接拿自己最后的程序測試,但是這里不建議這么做,建議先新建一個hello,world程序測試,成功后再調試自己的代碼。
- 文件夾位置和內容無所謂,但是最好簡單一些
cd ~/桌面 mkdir testvs cd testvs touch main.cpp gedit main.cpp
其中main.cpp代碼為:
#include <stdio.h> int main() { int a = 1; printf("hello worldn"); getchar(); return 0; }
(3)編譯,得到可執行文件
g++ main.cpp -o main -g
注意:
- 加-g選項,不然沒法用gdb調試
- 運行后testvs文件夾下有main.cpp和main兩個文件
(4)啟動gdbserver
(4.1)首先看一下自己的ubuntu系統ip地址:
hostname -I
可以得到本地ip地址為192.168.199.131
(4.2)啟動gdbserver(注意更改ip地址和測試文件目錄)
gdbserver 192.168.199.131:2000 ~/桌面/testvs/main
3.主機vscode設置
(1)首先在VScode中安裝下面幾個插件:
- C/C++
- C/C++ Extension Pack
- Remote – SSH
- Remote Development
(2)ssh遠程連接
左下角“管理”->”控制面板”,之后找到選項“Remote-SSH:Connect to Host…” -> Add New SSH Host…
輸入ubuntu系統ip地址,出來新界面
紅框內輸入ubuntu系統密碼,左下角顯示綠色ip地址即連接成功,如下圖。
(3)打開測試文件
打開文件夾 -> 選擇測試文件夾目錄,點“確定”按鈕
選中C/C++擴展,“在SSH:XXX中安裝”。C/C++ Extension Pack擴展同理
然后重啟Vscode和Ubuntu中的gdbserver(一定得要重啟,否則接下來的步驟會報錯)重新執行上述遠程連接流程。
(4)設置配置文件
(4.1)配置tasks.json
從菜單欄選擇Terminal>Configure Default Build Task, 在下拉欄里選擇C/C++: g++ build active file. 之后生成tasks.json文件,將內容更換為:
{ // 有關 tasks.json 格式的文檔,請參見 // https://go.microsoft.com/fwlink/?LinkId=733558 "version": "2.0.0", "tasks": [ { "type": "shell", "label": "g++ build active file", "command": "/usr/bin/g++", "args": [ "-std=c++11", "-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}" ], "options": { "cwd": "/usr/bin" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true } }, { //刪除二進制文件 "type": "shell", "label": "delete output file", "command": "rm", "args": [ "${fileDirname}/${fileBasenameNoExtension}" ], "presentation": { "reveal": "silent", //刪除過程不切換終端(專注程序輸出) } } ] }
(4.2)配置launch.json
在菜單欄選擇Debug>Add Configuration, 選擇C++ (GDB/LLDB), 在下拉欄中選擇g++ build and debug active file.生成launch.json,內容更改為:
{ // 使用 IntelliSense 了解相關屬性。 // 懸停以查看現有屬性的描述。 // 欲了解更多信息,請訪問: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "g++ build and debug active file", "type": "cppdbg", "request": "launch", "program": "${fileDirname}/${fileBasenameNoExtension}", "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false, "MIMode": "gdb", "setupCommands": [ { "description": "為 gdb 啟用整齊打印", "text": "-enable-pretty-printing", "ignoreFailures": true } ], "preLaunchTask": "g++ build active file", "postDebugTask": "delete output file", "miDebuggerPath": "/usr/bin/gdb" } ] }
4.運行調試
在main.cpp下調試運行即可
更多關于VSCode的相關知識,請訪問:VScode!