Skip to content

Arty3/Annotations

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 

Repository files navigation

C/C++ Annotations

A single-header, cross-platform annotation / decorator vocabulary for C and C++.

Overview

The goal of this header is to bridge the gap between:

  • what the developer knows or intends, and
  • what the compiler can infer automatically

It does so by exposing a consistent set of macros that map to:

  • standard language attributes when available,
  • compiler-specific attributes and builtins when necessary,
  • safe fallbacks when neither is supported.

The result is code that:

  • documents intent locally,
  • guides compiler optimizations,
  • makes contracts and assumptions explicit,
  • remains readable and searchable,
  • works cross-platform.

Design Principles

  • Intent-first Annotations exist to state what the developer believes about the code.

  • Language extension mindset This header is intended to act as a lightweight, optional language extension for C/C++. It does not introduce new semantics, but exposes existing compiler and language features in a uniform, explicit and readable way.

  • Decorator-style usage Most annotations are written as standalone tokens, ideally placed on the line above declarations.

  • Readable everywhere No leading/trailing underscores, no cryptic prefixes.

  • Portable by default Language standard is preferred; compiler extensions are used as fallbacks.

  • Explicit trade-offs
    Some annotations enable undefined behavior if misused. This is intentional and documented.

Non-goals

This header does not:

  • replace defensive runtime validation,
  • guarantee correctness or safety,
  • abstract away platform behavior,
  • attempt to normalize performance across architectures.

Annotations express intent, they do not enforce correctness by themselves.


Setup

  • annotations.h is a single-header library.
  • Simply include it in your project:
    • Ideally after standard library headers.
  • The header:
    • detects compiler, platform, architecture, and language standard,
    • optionally undefines any previously defined macros with the same names (opt-in),
    • then defines its own consistent set.

Important Notes

  • By default, the header does not undefine existing macros.
  • Defining ANNOTATIONS_REDEFINE to 1 before including the header enables a “clean-slate” mode, where all macros provided by annotations.h are first undefined.
  • When ANNOTATIONS_REDEFINE is enabled, any user-defined macros with the same names will be overridden.
  • The header conditionally includes standard and compiler-specific headers as needed.
  • Supported environments:
    • Languages: C (C99–C23), C++ (C++11–C++23)
    • Compilers: GCC, Clang, MSVC
    • Platforms: Windows, Linux, macOS
    • Architectures: x86, x64, ARM32, ARM64

Examples

MALLOC_CALL(1) COLD_CALL
void* memory_map(size_t size)
{
	GUARANTEE(size, "size must not be zero");

	const void* map = mmap(
		NULL,
		size,
		PROT_READ   | PROT_WRITE,
		MAP_PRIVATE | MAP_ANONYMOUS,
		-1,
		0
	);

	if (UNLIKELY(map == MAP_FAILED))
		return NULL;

	return map;
}
HOT_CALL
static int decode_token(int token)
{
	if (token >= 0 && token <= 255) LIKELY
		return token_table[token];

	if (token == TOKEN_EOF)
		return -1;

	UNREACHABLE;
}
DEPRECATED("Use deliver_request_v2 instead")
API_CALL
int deliver_request(void* handle);

API_CALL
CONTRACT(size == sizeof(header_t), "size must be sizeof(header_t)", "error")
void send_header(const void* header, size_t size);
static THREAD_LOCAL TLS_MODEL int lock_depth;

HOT_CALL
void spin_lock_acquire(volatile int* RESTRICT lock)
{
	while (EXPECT_FALSE(__atomic_exchange_n(lock, 1, __ATOMIC_ACQUIRE)))
		CPU_RELAX();

	ASSUME(lock != NULL);
	++lock_depth;
}
ALWAYS_INLINE PURE_CALL NON_NULL_ARGS(1)
static uint32_t checksum32(const void* data, size_t size)
{
	const uint32_t* p = ASSUME_ALIGNED(data, 4);
	uint32_t hash = 0;

	for (size_t i = 0; i < size / 4; ++i)
		hash ^= p[i];

	return hash;
}

API Reference

This section documents every macro exposed by annotations.h, grouped by purpose.
Unless stated otherwise, all macros are available in both C and C++ and degrade gracefully when unsupported.


Header Setup

Definition Description
ANNOTATIONS_REDEFINE Must be defined by user, undefines all macros before defining

Example

#define ANNOTATIONS_REDEFINE 1
#include "annotations.h"
  • All definitions the header provides will now be undefined before re-defining them. This is useful to win conflicts with other headers, but can cause other headers to fail silently.

Compiler, Platform, and Language Detection

Definition Description
COMPILER_MSVC Defined when compiling with Microsoft Visual C++.
COMPILER_CLANG Defined when compiling with Clang.
COMPILER_GCC Defined when compiling with GCC.
COMPILER_VERSION Numeric compiler version (compiler-specific encoding).
PLATFORM_WINDOWS Defined when targeting Windows.
PLATFORM_LINUX Defined when targeting Linux.
PLATFORM_MACOS Defined when targeting macOS.
PLATFORM_UNIX Defined when targeting a Unix-like platform.
ARCH_X86 Defined when targeting 32-bit x86.
ARCH_X64 Defined when targeting 64-bit x86.
ARCH_ARM32 Defined when targeting 32-bit ARM.
ARCH_ARM64 Defined when targeting 64-bit ARM.
ARCH_32BIT Defined when target architecture is 32-bit.
ARCH_64BIT Defined when target architecture is 64-bit.
LANG_C Defined when compiling as C.
LANG_CPP Defined when compiling as C++.
C_VERSION Numeric C language standard version.
CPP_VERSION Numeric C++ language standard version.
C99, C11, C17, C23 True when compiling with at least the given C standard.
CPP11, CPP14, CPP17, CPP20, CPP23 True when compiling with at least the given C++ standard.

Static Assertions and Basic Utilities

Definition Description
STATIC_ASSERT(cond, msg) Compile-time assertion with message support.
INLINE Portable inline, including pre-C99 support.
DISCARD(x) Explicitly discard an expression value.
ASSERT(cond, msg) Runtime assertion with message.
GUARANTEE(cond, msg) Runtime assertion + compiler assumption (UB if false).

Inlining and Code Generation

Definition Description
FORCE_INLINE Force function inlining where supported.
ALWAYS_INLINE Alias for FORCE_INLINE.
NO_INLINE Prevent function inlining.
FLATTEN Inline all calls within the function’s call graph.
NO_RETURN Function never returns.

Diagnostics and Usage Annotations

Definition Description
NO_DISCARD Warn if return value is ignored.
NODISCARD Alias for NO_DISCARD.
MAYBE_UNUSED Suppress unused warnings.
DEPRECATED(msg) Mark entity as deprecated with message.
FALLTHROUGH Mark intentional switch fallthrough.

Purity, Constness, and Call Frequency

Definition Description
PURE Function has no side effects but may read globals.
PURE_CALL Alias for PURE.
CONST_CALL Function has no side effects and reads no globals.
HOT_CALL Function is expected to be called frequently.
COLD_CALL Function is expected to be called rarely.

Allocation and Memory Semantics

Definition Description
MALLOC_CALL(...) Function returns newly allocated, non-aliasing memory.
ALLOC_SIZE(...) Allocation size depends on given arguments.
ALLOC_ALIGN(n) Allocation alignment depends on argument n.
ALIGNED(n) Align variable or type to n bytes.
ALIGN(n) Alias for ALIGNED.
PACKED Pack structure without padding.
RESTRICT Pointer does not alias other pointers.

Nullability and Contracts

Definition Description
NO_NULL_ARGS All pointer arguments must be non-null.
NON_NULL_ARGS(...) Specific pointer arguments must be non-null.
RETURNS_NON_NULL Function never returns null.
CONTRACT(cond, msg, type) Emit compile-time diagnostic if condition holds.

Visibility, ABI, and Linkage

Definition Description
API_CALL Export symbol from shared library.
API_IMPORT Import symbol from shared library.
API_LOCAL Hide symbol from shared library exports.
CDECL C calling convention.
STDCALL Stdcall calling convention.
FASTCALL Fastcall calling convention.
THISCALL Thiscall calling convention.
VECTORCALL Vectorcall calling convention.
CONSTRUCTOR Run function before main.
DESTRUCTOR Run function after main.

Branch Prediction and Assumptions

Definition Description
LIKELY Hint that a branch condition is likely true.
UNLIKELY Hint that a branch condition is unlikely true.
EXPECT_TRUE(x) Evaluate x and hint it is usually true.
EXPECT_FALSE(x) Evaluate x and hint it is usually false.
COND_PROB(x, p) Hint probability p for condition x.
ASSUME(x) Assume condition is true (UB if false).
UNREACHABLE Mark code path as unreachable (UB if reached).

Caution

LIKELY and UNLIKELY may expand to attributes or function-like macros depending on language standard and compiler. The user is responsible for correct placement.

/* C17 & C++17 and under */
if (LIKELY(condition))
	...

/* C23 & C++20 and above */
if (condition) LIKELY
	...

Threading, TLS, and Concurrency

Definition Description
THREAD_LOCAL Thread-local storage specifier.
TLS_MODEL Specify TLS access model.
COMPILER_BARRIER() Prevent compiler reordering.
MEMORY_BARRIER() Prevent compiler and CPU reordering.
LOAD_BARRIER() Acquire memory barrier.
STORE_BARRIER() Release memory barrier.
CPU_RELAX() CPU pause / yield hint.

Prefetching and Cache Control

Definition Description
PREFETCH(addr, rw, locality) Prefetch memory into cache.
PREFETCH_READ(addr) Prefetch address for reading.
PREFETCH_WRITE(addr) Prefetch address for writing.
PREFETCH_LOCALITY_NONE No temporal locality hint.
PREFETCH_LOCALITY_LOW Low temporal locality hint.
PREFETCH_LOCALITY_MEDIUM Medium temporal locality hint.
PREFETCH_LOCALITY_HIGH High temporal locality hint.

Containers, Arrays, and Pointers

Definition Description
ARRAY_SIZE(arr) Number of elements in array.
ARRAY_END(arr) Pointer to one past last element.
OFFSET_OF(type, member) Byte offset of struct member.
CONTAINER_OF(ptr, type, member) Get struct pointer from member pointer.
OFFSET_PTR(ptr, off) Offset pointer by byte count.
PTR_DIFF(a, b) Byte difference between two pointers.
ASSUME_ALIGNED(ptr, a) Assume pointer alignment.

Arithmetic and Bit Utilities

Definition Description
MIN(a, b) Minimum of two values.
MAX(a, b) Maximum of two values.
CLAMP(x, lo, hi) Clamp value to range.
IS_POWER_OF_2(x) Check if value is power of two.
ALIGN_UP(val, align) Round up to alignment.
ALIGN_DOWN(val, align) Round down to alignment.
IS_ALIGNED(val, align) Check alignment.
BIT(n) Bit mask for bit n.
BIT_SET(val, n) Set bit n.
BIT_CLEAR(val, n) Clear bit n.
BIT_TOGGLE(val, n) Toggle bit n.
BIT_CHECK(val, n) Test bit n.

Endianness and Low-level Operations

Definition Description
ENDIAN_LITTLE Target is little-endian.
ENDIAN_BIG Target is big-endian.
ROTL32, ROTR32 32-bit bit rotations.
ROTL64, ROTR64 64-bit bit rotations.
BSWAP16, BSWAP32, BSWAP64 Byte swap operations.
CLZ32, CLZ64 Count leading zeros.
CTZ32, CTZ64 Count trailing zeros.
POPCOUNT32, POPCOUNT64 Population count.

Formatting and Debugging

Definition Description
FORMAT_PRINTF(fmt, va) Enable printf-style format checking.
FORMAT_SCANF(fmt, va) Enable scanf-style format checking.
DEBUG_BREAK() Trigger debugger breakpoint.
UNUSED_VAR(...) Suppress unused value warnings.

License

MIT License. See the LICENSE file for details.

About

A single-header, cross-platform annotation / decorator vocabulary extension for C and C++.

Resources

License

Stars

Watchers

Forks

Contributors

Languages