下面都是在连接好了ssh后的操作
1. 创建c++文件
- 在项目文件夹中创建一个 C++ 源文件,例如 main.cpp,并写入以下示例代码:
#include <iostream>
int main() {
std::cout << "Hello, Raspberry Pi!" << std::endl;
return 0;
}
2. 配置tasks.json以编译c++项目:
- 按 Ctrl + Shift + P 打开命令面板,输入并选择 Tasks: Configure Task。
- 选择 Create tasks.json file from template。
- 选择 Others 创建一个自定义的任务配置文件。
这时会生成一个 tasks.json 文件,配置如下:
{
"version": "2.0.0",
"tasks": [
{
"label": "Build C++",
"type": "shell",
"command": "g++",
"args": [
"-g", // 生成调试信息
"main.cpp", // 需要编译的源文件
"-o", "main" // 输出可执行文件
],
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": ["$gcc"],
"detail": "Generated task for compiling C++"
}
]
}
3. 配置调试
- 在 VSCode 中,按 Ctrl + Shift + D 打开调试视图,点击 create a launch.json file。
- 选择 C++ (GDB/LLDB),然后选择适合的配置(例如 Linux)。
- launch.json 配置文件如下:
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug C++",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/main", // 你的可执行文件
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"miDebuggerPath": "/usr/bin/gdb", // 如果没有安装 gdb,可以通过 `sudo apt install gdb` 安装
"preLaunchTask": "Build C++", // 引用之前定义的构建任务
"linux": {
"MIDebuggerPath": "/usr/bin/gdb"
},
"osx": {
"MIDebuggerPath": "/usr/bin/lldb"
},
"windows": {
"MIDebuggerPath": "C:/mingw/bin/gdb.exe"
}
}
]
}
4. 编译和调试c++项目
-
编译项目:
按 Ctrl + Shift + B 或在命令面板中选择 Tasks: Run Build Task,VSCode 会自动调用你配置的 g++ 编译任务,编译 main.cpp 并生成 main 可执行文件。 -
调试项目:
按 F5 启动调试,VSCode 会自动运行 GDB 调试器来调试你的程序。如果程序正常编译并运行,应该会看到输出 Hello, Raspberry Pi!。