Dieses Beispiel trennt wiederverwendbaren C++-Code von der Anwendung und ergänzt einen kleinen automatischen Test. So wird aus einem Prototyp ein wartbares Projekt.
Projektstruktur
math-demo/
CMakeLists.txt
src/math.hpp
src/math.cpp
tests/test_math.cpp
CMakeLists.txt
cmake_minimum_required(VERSION 3.20)
project(MathDemo LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_library(vibe_math src/math.cpp)
target_include_directories(vibe_math PUBLIC src)
enable_testing()
add_executable(math_tests tests/test_math.cpp)
target_link_libraries(math_tests PRIVATE vibe_math)
add_test(NAME math_tests COMMAND math_tests)
src/math.hpp
#pragma once
int clamp_score(int value, int minimum, int maximum);
src/math.cpp
#include "math.hpp"
#include <algorithm>
int clamp_score(int value,int minimum,int maximum){
return std::clamp(value,minimum,maximum);
}
tests/test_math.cpp
#include "math.hpp"
#include <cassert>
int main(){
assert(clamp_score(5,0,10)==5);
assert(clamp_score(-2,0,10)==0);
assert(clamp_score(99,0,10)==10);
}
Kompilieren und testen
cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure
Release-Build
cmake -S . -B build-release -DCMAKE_BUILD_TYPE=Release
cmake --build build-release
Nächste Iterationen
- Weitere mathematische Funktionen ergänzen
- Compiler-Warnungen als Fehler behandeln
- Tests in GitHub Actions ausführen