C++项目的CI/CD:配置GitHub Actions

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

C++ 项目的 CI/CD:配置 GitHub Actions



现代 C++ 开发不仅需要编写高质量的代码,还需要配置构建、测试和部署流程。CI/CD(持续集成/持续部署)是一种实践,可以自动化这些流程,缩短从编写代码到交付给用户的时间。在本文中,我们将探讨如何使用 GitHub Actions(一个强大且内置于 GitHub 的免费工具)为 C++ 项目配置 CI/CD。



GitHub Actions 允许创建自动工作流程(workflows),这些工作流程在特定事件(如推送到仓库、创建 pull request、发布等)时触发。对于 C++ 项目来说,这尤其有用,因为它可以确保代码在不同平台上都能构建,并且不包含回归错误。



适用于 C++ 的 GitHub Actions 基础



GitHub Actions 使用 YAML 文件来描述 workflows。每个 workflow 由一个或多个在虚拟机(runners)上执行的 jobs 组成。对于 C++ 项目,通常使用 Ubuntu、Windows 和 macOS runners。让我们来看一个 workflow 文件的基本结构。



name: C++ CI

on: push: branches: [ main, develop ] pull_request: branches: [ main ]

jobs: build: runs-on: ubuntu-latest

steps: - uses: actions/checkout@v4

- name: Install dependencies run: | sudo apt-get update sudo apt-get install -y cmake g++ libboost-all-dev

- name: Configure CMake run: cmake -B build -DCMAKE_BUILD_TYPE=Release

- name: Build run: cmake --build build --config Release

- name: Test run: cd build && ctest --output-on-failure


这个 workflow 在推送到 main 和 develop 分支以及创建针对 main 的 pull request 时触发。它会安装依赖项(CMake、g++、Boost),配置项目,构建项目并运行测试。



C++ 项目的多平台构建



C++ 的 CI/CD 主要优势之一是能够自动检查在多个平台上的构建情况。这一点至关重要,因为 C++ 代码在不同的操作系统和编译器上可能表现不同。GitHub Actions 可以轻松组织构建矩阵。



jobs:  build:    strategy:      matrix:        os: [ubuntu-latest, windows-latest, macos-latest]        compiler: [g++, clang++]        include:          - os: ubuntu-latest            compiler: g++            cmake_flags: -DCMAKE_CXX_COMPILER=g++-11          - os: ubuntu-latest            compiler: clang++            cmake_flags: -DCMAKE_CXX_COMPILER=clang++-14          - os: windows-latest            compiler: msvc            cmake_flags: -DCMAKE_CXX_COMPILER=cl          - os: macos-latest            compiler: clang++            cmake_flags: -DCMAKE_CXX_COMPILER=clang++

runs-on: ${{ matrix.os }}

steps: - uses: actions/checkout@v4

- name: Install dependencies (Ubuntu) if: matrix.os == 'ubuntu-latest' run: | sudo apt-get update sudo apt-get install -y cmake g++-11 clang-14 libboost-all-dev

- name: Install dependencies (macOS) if: matrix.os == 'macos-latest' run: | brew update brew install cmake boost

- name: Install dependencies (Windows) if: matrix.os == 'windows-latest' run: | choco install cmake boost-msvc-14.3

- name: Configure CMake run: cmake -B build ${{ matrix.cmake_flags }} -DCMAKE_BUILD_TYPE=Release

- name: Build run: cmake --build build --config Release

- name: Test run: | if [ "${{ runner.os }}" == "Windows" ]; then cd build && ctest -C Release --output-on-failure else cd build && ctest --output-on-failure fi


在这个例子中

博客

书籍推荐