You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否通过VS Code借助VirtualBox虚拟机运行POSIX兼容的pthreads C程序?

实现Windows主机VS Code编写pthreads代码并在Ubuntu虚拟机运行的方案

前置准备

  • 确保Ubuntu虚拟机开启SSH服务:
    1. 在Ubuntu终端执行 sudo apt update && sudo apt install openssh-server
    2. 启动服务 sudo systemctl start sshd,设置开机自启 sudo systemctl enable sshd
    3. 执行 ip addr show 查看并记录虚拟机的IP地址(一般在网卡字段的inet项中)

VS Code配置步骤

  • 安装必要扩展:

    • Remote - SSH:用于远程连接Ubuntu虚拟机
    • C/C++ Extension Pack:提供C代码的语法高亮、智能提示及编译调试支持
  • 连接Ubuntu虚拟机:

    1. 打开VS Code,按F1调出命令面板,输入 Remote-SSH: Connect to Host...
    2. 选择 Add New SSH Host,输入 ssh 虚拟机用户名@虚拟机IP(例如ssh ubuntu@192.168.56.101)
    3. 选择默认配置文件保存路径,点击连接后输入虚拟机用户密码完成远程连接

代码编写与运行配置

  • 创建并编写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;
    }
    
  • 配置编译任务:

    1. 按Ctrl+Shift+B调出编译面板,选择 Create tasks.json file from template → Others
    2. 修改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"
              }
          ]
      }
      
    3. 再次按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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 18:45:06