English | 简体中文
A header-only C library for safe numerical calculations, primarily designed to prevent various arithmetic overflows.
This library currently provides calculation functions for the following types:
- Unsigned integers: addition, subtraction, multiplication, division, and modulo.
- Signed integers: addition, subtraction, multiplication, division, modulo, and negation.
Among them,
- Division and modulo calculations support zero-division detection.
- Both unsigned and signed integers cover all unsigned/signed integer types strictly supported by the C99 and later standards.
For details, please refer to the API Reference.
Requirements: CPM.cmake.
In CMakeLists.txt:
include(${PROJECT_SOURCE_DIR}/cmake/CPM.cmake)
CPMAddPackage("gh:mtueih/safe_calc#v1.0.1")In CMakeLists.txt:
find_package(safe_calc REQUIRED)In CMakeLists.txt:
target_link_libraries(your_target PRIVATE safe_calc::safe_calc)#include <safe_calc/safe_calc.h>#include <safe_calc/safe_calc.h>
#include <stddef.h>
int main(void)
{
int a, b, result;
a = 1;
b = 2;
/* Check only. */
if (safe_int_add(a, b, NULL) == SAFE_CALC_OK)
{
printf("[%d + %d] will not overflow.\n", a, b);
}
/* Perform the calculation. */
if (safe_int_add(a, b, &result) == SAFE_CALC_OK)
{
printf("%d + %d = %d\n", a, b, result);
}
return 0;
}- CMake 3.24+.
- A C compiler that supports C99+ (MSVC / MinGW-w64 / Clang).
git clone https://github.com/mtueih/safe_calc.git --depth 1 -b v1.0.1
cd safe_calccmake -B build -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF -DSAFE_CALC_INSTALL=ON
cmake --build build --config Release --parallel
cmake --install build --config Release --strip --prefix installNotes on the above commands:
- Installation command: Using
--prefix installinstalls the artifacts into theinstalldirectory instead of a system-wide location, so you can use the installed artifacts in your preferred way. If you want a system-wide installation, simply omit the--prefixoption.
This project is licensed under the ISC License — see the LICENSE file for details.