Skip to content
mtueihPublic

About

A header-only C library for safe numerical calculations, primarily designed to prevent various arithmetic overflows.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

77 Commits

Folders and files

Repository files navigation

English | 简体中文

safe_calc

C Standard CMake GitHub License CI

A header-only C library for safe numerical calculations, primarily designed to prevent various arithmetic overflows.

API

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.

Using in Other Projects

Adding the Dependency

CPM.cmake

Requirements: CPM.cmake.

In CMakeLists.txt:

include(${PROJECT_SOURCE_DIR}/cmake/CPM.cmake)

CPMAddPackage("gh:mtueih/safe_calc#v1.0.1")

CMake find_package (requires installation)

In CMakeLists.txt:

find_package(safe_calc REQUIRED)

Linking the Library

In CMakeLists.txt:

target_link_libraries(your_target PRIVATE safe_calc::safe_calc)

Using in Code

Including the Header

#include <safe_calc/safe_calc.h>

Using Library Functions

#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;
}

Building from Source

Requirements

Build Steps

Clone the Repository

git clone https://github.com/mtueih/safe_calc.git --depth 1 -b v1.0.1
cd safe_calc

Configure, Build, and Install

cmake -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 install

Notes on the above commands:

  • Installation command: Using --prefix install installs the artifacts into the install directory 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 --prefix option.

License

This project is licensed under the ISC License — see the LICENSE file for details.

About

A header-only C library for safe numerical calculations, primarily designed to prevent various arithmetic overflows.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages