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.
// 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; }
Control flow:
__attribute__((noreturn)): function never returns__attribute__((noreturn, cold)): rarely calledPurity:
__attribute__((pure)): no side effects, reads globals/params__attribute__((const)): only depends on parametersInitialization/cleanup:
__attribute__((constructor)): run before main__attribute__((destructor)): run after main__attribute__((constructor(101)))Deprecation and warnings:
__attribute__((deprecated("use X instead"))): compiler warns__attribute__((unused)): suppress unused warningsFormat checking:
__attribute__((format(printf, 1, 2))): check printf argsOptimization hints:
__attribute__((hot)): frequently called__attribute__((cold)): rarely called__attribute__((aligned(N))): align to N bytesPortability:
__declspec syntax#ifdef __GNUC__Best practices: