使用容器通过 Visual Studio Code 生成和调试

如果使用 Visual Studio Code 进行应用程序开发,则可以设置项目,使其在容器内生成。 然后,可以直接在容器中生成和调试。 本主题假定你已创建一个具有 Visual Studio Code 的项目,以便 .vscode 目录存在,并且具有两个文件 launch.json 和 settings.json。

本主题讨论在本地使用容器; 使用 GitHub Codespaces 进行生成和调试 介绍了如何使用 GitHub Codespaces 编辑、生成、部署和调试 Azure Sphere 应用。

设置 .devcontainer 文件夹

在项目的顶级目录中,创建名为 .devcontainer 的文件夹。 在此文件夹中,创建包含以下内容的名为 devcontainer.json 的文件:

{
    "name": "Azure Sphere Blink",
    "runArgs": [ "--cap-add=SYS_PTRACE", "--security-opt", "seccomp=unconfined"],
    "build": {
    "dockerfile": "Dockerfile",
    "target": "dev"
    },

    // Use 'settings' to set *default* container specific settings.json values on container create.
    // You can edit these settings after create using File > Preferences > Settings > Remote.
    "settings": {
            "terminal.integrated.shell.linux": "/bin/bash"
    },

    // Use 'appPort' to create a container with published ports. If the port isn't working, be sure
    // your server accepts connections from all interfaces (0.0.0.0 or '*'), not just localhost.
    // "appPort": [],

    // Uncomment the next line to run commands after the container is created.
    // "postCreateCommand": "gcc -v",

    // Comment out the next line if you want to run as root instead
    "remoteUser": "vscode",

    // Add the IDs of extensions you want installed when the container is created in the array below.
    "extensions": [
    "ms-vscode.cpptools",
    "ms-vscode.azure-sphere-tools",
    "ms-vscode.azure-sphere-tools-ui"
    ]
}

接下来,在 .devcontainer 文件夹中创建一个名为 Dockerfile 的文件,其中包含以下内容:

FROM mcr.microsoft.com/azurespheresdk:latest AS dev

FROM dev AS build
COPY ./ /src/
WORKDIR /out
RUN cmake -G "Ninja" -DCMAKE_TOOLCHAIN_FILE="/opt/azurespheresdk/CMakeFiles/AzureSphereToolchain.cmake" \
    -DAZURE_SPHERE_TARGET_API_SET="latest-lts" -DCMAKE_BUILD_TYPE="Release" "/src"
ENTRYPOINT [ "ninja" ]

初始 FROM 行将标准 Azure Sphere Docker 映像指定为基本开发容器,第二行指定使用该基本容器作为生成环境。 该 COPY 行将存储库的内容复制到容器的 /src/ 目录中。 指定 WORKDIR 生成目录。 命令 RUN 提供 CMake 命令来生成生成文件。 最后, ENTRYPOINT 指定应调用 ninja 来实际生成应用程序。

生成和调试项目

在 Visual Studio Code 中打开项目文件夹。 Visual Studio Code检测到新文件并打开一个消息框,指出“文件夹包含开发容器配置文件。 重新打开文件夹以在容器中开发。”选择“在容器中重新打开”按钮,重新打开由 .devcontainer/Dockerfile 文件创建的容器中的文件夹。 中的标题栏Visual Studio Code更改,以显示你在容器中编辑。 如果打开左侧导航栏中的“扩展”选项卡,会看到本地安装的扩展和容器中安装的扩展。

按 F5 生成项目并开始调试。 应用程序像往常一样生成并旁加载到设备。 如果在代码中设置了断点,则应用将运行,直到到达断点。 可以使用常用的调试命令来演练代码。 有关更多详细信息,请参阅Visual Studio Code文档中的调试主题。

完成调试后,按 Shift+F5 或停止图标。 若要关闭容器,请使用Visual Studio Code工具栏上的“远程”菜单中的“关闭远程连接”命令。