在Windows上使用VSCode遠程鏈接到Linux上開發並調試C++程序
開發環境配置成功,記個流水賬
Linux安裝相應工具
apt install -y gcc make gdb
請配置好Linux端的SSH功能
給VSCode安裝Remote Development
擴展
安裝后可以看到一個新圖標,點擊后選中SSH Targets
添加鏈接方式
編輯這個文件,如果沒有就新建:
C:/Users/用戶名/.ssh/config
以下內容添加到末尾后編輯下:
Host 設備名稱(不影響連接)
HostName Linux的地址(域名或ip)
Port 端口
PreferredAuthentications 驗證方式(password或publickey)
User 用戶名
IdentityFile 私鑰文件全路徑,如果上面選擇了publickey,需要用這個指出私鑰文件的全路徑
例子:
Host 新設備
HostName 10.0.1.45
PreferredAuthentications password
Port 142
User root
編輯完之后保存即可看到VSCode顯示了新添加的鏈接方式:
鏈接
右鍵點擊鏈接方式,選則一種打開方法(在當前VSCode打開或新開一個VSCode打開):
不管你上面選擇哪個,后續都會讓你選擇系統類型,如果你是以密碼方式驗證,還會讓你輸入密碼:
鏈接成功,接着打開個目錄試試:
會列出Linux的文件系統,讓你選擇工作目錄,選好后點擊旁邊的OK即可:
如果使用密碼驗證,此處有可能會讓你再輸入一次密碼.后面很多步驟也有可能反復驗證,如果可以盡可能使用證書驗證,會流暢很多.
打開成功.可以看到目錄里面什么都沒有,下一步創建工程:
創建工程
給Linux端安裝VSCode擴展
注意,這些擴展必須安裝到Linux端,VSCode需要鏈接上去再安裝!
新建文件main.c
:
#include<stdio.h>
void main()
{
int a=0;
a++;
a+=2;
a-=3;
printf("a=%d\n",a);
return;
}
新建文件Makefile
:
# C compiler options
CC = gcc
#CFLAGS = -g -O2
RELEASE = release.elf
DEBUG = debug.elf
LIBS =
INC =
# Source files
SRCS = main.c
# Make everything
all: $(RELEASE) $(DEBUG)
# Make the application
$(RELEASE): $(OBJS)
$(CC) -o $(RELEASE) $(SRCS) $(LIBS)
$(DEBUG): $(OBJS)
$(CC) -o $(DEBUG) $(SRCS) $(LIBS) -ggdb3
#
# Clean all object files...
#
clean:
$(RM) $(DEBUG) $(RELEASE)
新建文件.vscode/tasks.json
:
{
"version": "2.0.0",
"tasks": [
{
"label": "make",
"command": "make",
"type": "process",
"args": [],
"problemMatcher": "$msCompile"
}
]
}
新建文件.vscode/launch.json
:
{
// 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": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/debug.elf",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"logging": {
"moduleLoad": true,
"engineLogging": true,
"trace": true
},
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "make",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
開始調試
按F5,選擇工程類型:
選擇gcc版本:
可以看到VSCode成功進入調試模式,左邊還能顯示所有變量的值: