在linux下配置VSCode的開發環境
工欲善其事,必先利其器
- 系統:Manjaro
- 內核版本:5.4.24
- gcc 版本:9.2.1
- VSCode:1.43.0
VSCode下載
由於我的Linux機是Manjaro(一個ArchLinux的版本),安裝VSCode方式還和傳統的Debian系以及RedHat系不一樣。
正常情況下Arch版本可以通過如下方式安裝
$ sudo pacman -S visual-studio-code-bin
但我這系統提示簽名未知信任,文件已損壞。所以直接上官網下載壓縮包。
下載tar.gz
壓縮包並解壓。
准備環境
- 創建工程項目目錄
$ cd ~
$ mkdir -p workspace/clang/helloworld # 創建helloworld目錄
$ cd workspace/clang/helloworld
- 安裝編譯環境
VSCode只是個編輯器,編譯工作仍然需要用戶提供編譯環境。
使用version
或whereis
來確保你的電腦安裝了g++
,gdb
$ g++ --version
$ gdb --version
$ whereis g++
$ whereis gdb
這里我的電腦一開始whereis gdb
顯示有路徑如下,但是無法調用version
這樣是不行的
$ whereis gdb
gdb: /usr/share/gdb
如果沒有安裝,則使用對應linux系列的命令進行安裝,Manjaro情況如下
$ pacman -S g++ gdb
啟動VS Code
切換到工程文件夾目錄,啟動vscode,或者直接將目錄文件夾拖入vscode。
接下來會的操作會自動在工程目錄下建立一個.vscode
文件夾,並在文件夾下建立,這些不需要手動進行
c_cpp_properties.json
:編譯器路徑配置task.json
:編譯時的命令配置launch.json
:Debug配置
寫代碼
- 新建
helloworld.cpp
文件,寫入每門語言的第一個程序Hello world
#include <iostream>
#include <string>
using namespace std;
int main(){
cout << "Hello, world! from VS Code!" << endl;
}
- 安裝C/C++插件
在左側的插件選項卡里,搜索C++,安裝微軟的那個C/C++
就行
回到helloworld.cpp
,接着我們創建tasks.json
,告訴VS Code如何編譯該程序。
- 通過菜單的
Terminal>Configure Default Build Task
。你會看到一個下拉框,選擇C/C++:g++ build active file
這時候,在你的目錄下會多出一個.vscode
文件夾,里面自動生成了tasks.json
。
內容大致如下
{
// task.json
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "g++ build active file",
"command": "/usr/bin/g++",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "/usr/bin"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
command
用來設置編譯器,這里是g++
的路徑。args
就是平時在命令行下,g++命令后面的參數。這里的編譯文件為當前文件${file},編譯輸出為同一路徑下的同名無后綴文件即helloworld
。
- 回到
helloworld.cpp
,通過菜單Terminal>Run Build Task
來完成編譯。如果成功終端輸入如下
- 在終端中運行,輸入命令
./helloworld
#include錯誤
若C程序中總有下划線,並且提示有檢測到#include錯誤。請更新includePath
- 通過
Ctrl+Shift+P
打開命令導航,運行命令C/C++: Edit Configurations(UI)
在includePath
中添加,g++的位置include位置
通過命令$ g++ -v -E -x c++ -
來查看,只需添加如圖兩個
此時會自動生成c_cpp_properties.json
文件
調試
- 通過菜單
Run>Add Configuration
,選擇C++ (GDB/LLDB)>g++ build and debug active file
來創建launch.json
文件
文件內容大致如下
{
// launch.json
"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",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
其中miDebuggerPath
是gdb的路徑,另外還可以將stopAtEntry
設置為true
這樣在進入主函數時自動設置斷點。
完成
至此,一個項目的創建,編譯,調試都已經可以在VS Code下進行。
作者:SA19225176,萬有引力丶
參考資料來源:USTC SE2020高級軟件工程