Table of Contents

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:

Purity:

Initialization/cleanup:

Deprecation and warnings:

Format checking:

Optimization hints:

Portability:

Best practices: