能否通过VS Code借助VirtualBox虚拟机运行POSIX兼容的pthreads C程序?
实现Windows主机VS Code编写pthreads代码并在Ubuntu虚拟机运行的方案
前置准备
- 确保Ubuntu虚拟机开启SSH服务:
- 在Ubuntu终端执行
sudo apt update && sudo apt install openssh-server - 启动服务
sudo systemctl start sshd,设置开机自启sudo systemctl enable sshd - 执行
ip addr show查看并记录虚拟机的IP地址(一般在网卡字段的inet项中)
- 在Ubuntu终端执行
VS Code配置步骤
安装必要扩展:
- Remote - SSH:用于远程连接Ubuntu虚拟机
- C/C++ Extension Pack:提供C代码的语法高亮、智能提示及编译调试支持
连接Ubuntu虚拟机:
- 打开VS Code,按
F1调出命令面板,输入Remote-SSH: Connect to Host... - 选择
Add New SSH Host,输入ssh 虚拟机用户名@虚拟机IP(例如ssh ubuntu@192.168.56.101) - 选择默认配置文件保存路径,点击连接后输入虚拟机用户密码完成远程连接
- 打开VS Code,按
代码编写与运行配置
创建并编写C代码:
在远程窗口(已连接Ubuntu)中新建文件夹和.c文件,示例thread_demo.c代码:#include <stdio.h> #include <pthread.h> void *thread_func(void *arg) { printf("Hello from pthread!\n"); pthread_exit(NULL); } int main() { pthread_t tid; pthread_create(&tid, NULL, thread_func, NULL); pthread_join(tid, NULL); return 0; }配置编译任务:
- 按
Ctrl+Shift+B调出编译面板,选择Create tasks.json file from template→Others - 修改
tasks.json内容为如下编译pthreads代码的配置:{ "version": "2.0.0", "tasks": [ { "label": "Compile pthread code", "type": "shell", "command": "gcc thread_demo.c -o thread_demo -lpthread", "group": { "kind": "build", "isDefault": true }, "problemMatcher": ["$gcc"], "detail": "Compile C code with pthread library" } ] } - 再次按
Ctrl+Shift+B执行编译,生成可执行文件
- 按
运行程序:
打开VS Code内置终端(已关联Ubuntu虚拟机),执行./thread_demo即可查看输出结果
调试配置(可选)
- 按
F5调出调试面板,选择C++ (GDB/LLDB)生成launch.json,修改内容如下:
完成配置后按{ "version": "0.2.0", "configurations": [ { "name": "Debug pthread program", "type": "cppdbg", "request": "launch", "program": "${workspaceFolder}/thread_demo", "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false, "MIMode": "gdb", "setupCommands": [ { "description": "Enable pretty-printing for gdb", "text": "-enable-pretty-printing", "ignoreFailures": true } ], "preLaunchTask": "Compile pthread code" } ] }F5即可启动调试
内容的提问来源于stack exchange,提问作者Vled
相关产品推荐
相关产品推荐

