以下推荐一个使用远端服务器开发调试的方法,可以让我们像在本地编写调试程序一样简单:使用vscode + vscode-remote插件
一、安装SSH
1.windows自带的openssh经测试不可用,建议先安装git,使用git中自带的ssh,方法如下:首先从git官网下载git安装包,然后一路默认安装完成,在桌面打开git bash,输入指令where ssh,检测系统中现有的ssh可执行文件,应该显示有两个,一个是图中的git下的ssh.exe,另一个是windows的Openssh(我的截图中是已经删除过的)。

2.为了使用git中的ssh作为默认ssh工具,我们需要在windows的设置->应用->可选功能中,找到OpenSSH,然后选择卸载它。卸载了windows的ssh后,我们需要将git的ssh目录添加到系统的环境变量的path中,根据刚才where ssh打印的信息,要添加的目录应该为C:\Program Files\Git\usr\bin\(环境变量在我的电脑右键,属性->高级系统设置->环境变量->系统变量->path)。


3.完成后再去git bash中执行where ssh,此时应该只有一个git中的ssh路径了。如果不行,建议重启电脑。

二、安装remote development
1.打开vscode,搜索扩展remote development,这一步会下载多个扩展,相互依赖:

2.安装完右侧会显示出一个新的开发窗口,此时按F1,在命令框中输入搜索Remote-SSH:Connect to Host->configure SSH Hosts,->C:/Users/用户名/.ssh/config。




3.配置方法,实验室的服务器配置了代理,需要一个代理工具,这里找到一个可用的windows工具ncat(有个叫netcat的工具,实测不行,别搞混了;另外,使用git携带的connect工具也可以实现,命令可以google),下载ncat后移动到C:\Windows\system32\目录下,确保windows能找到ncat指令。
代理指令为:ProxyCommand ncat --proxy <代理机IP>: <代理端口> %h %p
补充connect代理指令:ProxyCommand connect -S <代理机IP>: <代理端口> %h %p
ip按照常规方法配置,配置完ctrl+s保存。

4.配置完后列表出现一个服务器

5.按F1,输入remote-ssh setting,找到show log terminal,勾选。
点击右端的按钮开始连接,首次登录需要输入密码,且等待安装远程服务,比较慢。
三、向服务端添加密钥,实现免密访问
1.个人认为这一点比较必要,因为不止连接时会需要密码,打开目录时也会,免密方便很多。
2.方法是打开git bash,因为用的是git的ssh,所以用git bash配置, 首先在客户端生成ssh密钥:
ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa
3.将公钥传到服务端:
ssh-copy-id -o ProxyCommand="ncat --proxy <代理机IP>: <代理端口> %h %p" root\@host_IP
4.最后一步传输配置了代理,不配置代理命令传不过去。
四、打开服务器文件夹
1.打开vscode后,配置了密钥会自动链接服务器,然后会显示这个链接界面,如果没有配置密钥会要求输入密码,注意查看terminal。

2.登录后,打开exploer选项卡,然后会有个打开文件夹的按钮,上面还有一行字,写着已经链接到了远程端。点击后选择一个服务端的文件夹打开,然后等就好了,这个速度特别慢,要从服务端下载,所以耐心等,建议不要打开较大的目录,因为速度慢,延迟高,打开自己的工作目录就好。


五、使用vscode进行远程debug
1.安装好vscode-remote,我们连接上服务器并且打开工作区后(一定要确保debug的工程在当前工作区内,且最好不要多个工程放一个工作区里面),可以直接点击vscode左侧的run and debug窗口,点击 run and debug.

2.点击run and debug后,弹出的窗口中会让我们选择调试器,我们需要在服务器环境调试(确保服务器已经安装了gdb),因此选择C++(GDB/LLDB),

3.选择完调试器后,再弹出一个窗口会让我们选择编译器,因为vscode会在每次调试前帮我们编译程序(可选,可配置编译指令),大家根据自己的工程情况选择。

4.配置完后,vscode-remote默认会自动开启一次调试,但是大概率会失败,因为默认生成的配置文件不符合我们的调试要求,我们此时忽略这次错误的调试,打开我们的工程文件夹,会看到出现了一个.vscode隐藏文件夹,里面是debug的配置文件。

5.我们先打开launch.json,可以我们需要关注的第一个是program这个项目,这是debug时自动运行的可执行文件,默认是根据vscode的宏自动读取工作区文件,但是大概率会出错,比如我习惯将执行文件名字编译成main,但是vscode默认生成的执行文件名字为rmmio,是我的工程名。为了正常调试,我们直接将工程中的可行文件的绝对路径+可执行文件名填进去,比如我的工程,就改为/home/dingbo/Desktop/Reliable_MMIO/main
紧随program后面的配置项args是设置参数的,如果我们的执行文件有参数,可以一次加在args后面的[]中,格式为"参数1","参数2","参数3"

配置完gdb调试命令后,我们可以看到launch.json下还有一个preLaunchTask配置项,这个就是刚刚提到的,可以选择vscode在每次开启debug前为我们自动编译工程,编译最新版本的可执行文件。配置编译需要在在.vscode文件夹下的tasks.json中完成。我们可以看到这个文件中有两个重要的配置项,command和args,我们只需要将编译需要用到的命令依次填入其中即可,比如我用make 直接执行整个工程的编译,就可以按照如图所示更改。



六、配置完成后,我们可以直接点击run and debug中的这个绿色三角开始debug。

1.点击后,vscode上方正中间会出现一个调试工具框,包括了continue,step in等

2.我们可以在vscode图形界面中,找到行号左侧的位置,直接点击进行断点,而不需要在gdb中设置,打完的断点会显示在左侧工具栏中,


3.调试过程中,左侧工具栏第一行会自动实时显示显示当前程序运行位置的各种变量的值的变化

4.同时如果我们需要知晓其他变量的值,也可以在watch窗口中手动添加一个变量或者表达式。
