cmake 在CI/CD中将测试构建与应用构建分离,无需重建

amrnrhlw  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(166)

我有一个包含文件的项目:

main.cpp - application
sum.h
sum.cpp
tester.cpp - tester application

我用CMake和CMakeLists.txt来构建它:

cmake_minimum_required(VERSION 3.10)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

set (ProjectName hello)
project(hello VERSION 1.0)
set(SOURCES sum.h sum.cpp main.cpp)
add_executable(${ProjectName} ${SOURCES})

enable_testing()
add_executable(tester sum.h sum.cpp tester.cpp)
add_test(Tester tester)

然后我在gitlab上设置了一个CI/CD:

image: gcc

build:
  stage: build
  before_script:
   - apt update && apt -y install make cmake libcrypto++-dev
  script:
    - cd SimpleCiCdForCpp
    - mkdir build
    - cd build
    - cmake ..
    - make
    - ls
  artifacts:
    paths:
      - SimpleCiCdForCpp/build/hello
      - SimpleCiCdForCpp/build/tester

test:
  stage: test
  before_script:
   - apt update && apt -y install make cmake libcrypto++-dev
  script:
    - ls
    - cd SimpleCiCdForCpp
    - cd build
    - cmake ..
    - make
    - ctest

一切正常-我有2个应用程序:问题是我必须在构建阶段和测试阶段构建所有内容,否则我将以 ctest 的空测试配置结束。有什么好的做法可以将测试项目与主应用程序分开吗?

nvbavucw

nvbavucw1#

您的CMAkeLists.txt可能如下所示:

cmake_minimum_required(VERSION 3.10)
project(hello VERSION 1.0)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include(CTest) # Sets BUILD_TESTING=0 by default

# Do not build twice.

add_library(sum sum.cpp sum.h)

# There is already PROJECT_NAME CMake variable.

add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} PRIVATE sum)

# Do not use if not needed!

if(BUILD_TESTING)
  add_executable(tester tester.cpp)
  target_link_libraries(tester PRIVATE sum)
  # Use same name for test and executable.
  add_test(COMMAND tester NAME tester)
endif()

然后道:

build:
    - cmake -S. -Bbuild -DBUILD_TESTING=0
    - cmake --build build
  artifacts:
    paths:
      # Cache the... cache, so that you don't rebuild!
      - SimpleCiCdForCpp/build

test:
    - cmake -S. -Bbuild -DBUILD_TESTING=1
    - cmake --build build
    # Newest syntax.
    - ctest --test-dir build

相关问题