Site Tools


c-function-attributes

C function attributes

C function attributes (GCC/Clang) use __attribute__ to annotate functions with metadata: __attribute__((noreturn)) for functions that never return, __attribute__((pure)) for side-effect-free functions, __attribute__((constructor)) for initialization, etc. Enables compiler optimizations and checks.

Use function attributes to help the compiler optimize and verify code correctness.

Example

// compile: gcc -Wall -o func_attrs func_attrs.c
// run: ./func_attrs
// description: function attributes for optimization hints
 
#include <stdio.h>
#include <stdlib.h>
 
// Function never returns
void fatal_error(const char *msg) __attribute__((noreturn));
void fatal_error(const char *msg) {
    fprintf(stderr, "FATAL: %s\n", msg);
    exit(1);
}
 
// Pure function: no side effects, only reads args
int square(int x) __attribute__((pure));
int square(int x) {
    return x * x;
}
 
// Const function: even stricter than pure
int add_one(int x) __attribute__((const));
int add_one(int x) {
    return x + 1;
}
 
// Constructor: called before main
void initialize(void) __attribute__((constructor));
void initialize(void) {
    printf("Initialization function\n");
}
 
// Destructor: called after main
void cleanup(void) __attribute__((destructor));
void cleanup(void) {
    printf("Cleanup function\n");
}
 
// Deprecated function
void old_function(void) __attribute__((deprecated("use new_function instead")));
void old_function(void) {
    printf("Old function\n");
}
 
int main() {
    printf("Main function\n");
    int result = square(5);
    printf("5^2 = %d\n", result);
 
    return 0;
}

Common attributes

Control flow:

  • __attribute__((noreturn)): function never returns
  • __attribute__((noreturn, cold)): rarely called
  • Enables dead code elimination

Purity:

  • __attribute__((pure)): no side effects, reads globals/params
  • __attribute__((const)): only depends on parameters
  • Enables loop invariant motion

Initialization/cleanup:

  • __attribute__((constructor)): run before main
  • __attribute__((destructor)): run after main
  • Priority: __attribute__((constructor(101)))

Deprecation and warnings:

  • __attribute__((deprecated("use X instead"))): compiler warns
  • __attribute__((unused)): suppress unused warnings

Format checking:

  • __attribute__((format(printf, 1, 2))): check printf args
  • Position 1 = format string param, 2 = variadic start

Optimization hints:

  • __attribute__((hot)): frequently called
  • __attribute__((cold)): rarely called
  • __attribute__((aligned(N))): align to N bytes

Portability:

  • GCC/Clang only
  • MSVC has similar __declspec syntax
  • Portable code wraps in #ifdef __GNUC__

Best practices:

  • Document why attribute is needed
  • Use for correctness and safety, not minor optimization
  • Test on target compilers (behavior differs)
c-function-attributes.md · Last modified: by 127.0.0.1