Skip to content
systemcoding.dev
Toolchains

The Complete Guide to GCC Attributes and Builtins

A working tour of GCC attributes and builtins for C: function, variable and type attributes, the builtins worth knowing, and how to keep them portable.

29 min read
Summarize in AI
Flat illustration of source code passing through a compiler and linker into a binary, with the GNU, C and LLVM logos.

Standard C describes what a program means. GCC adds a second channel for everything the standard has no words for: this function never returns, this pointer is never null, this struct has no padding, this branch is almost never taken, this variable lives in a special memory section. That channel has two parts. Attributes are annotations you attach to declarations, written __attribute__((name)), that change how the compiler treats the thing you declared. Builtins are functions the compiler knows from the inside, spelled __builtin_name, that expand to instructions or to compile-time answers instead of calling a library. Clang implements most of both for compatibility, the Linux kernel and many large C projects lean on them, and the C23 standard has absorbed a handful of the most useful attributes into official syntax.

This guide is a field manual for working C programmers. It covers the syntax and the portability tools first, then function attributes, variable and type attributes, statement attributes and the builtins in the order you are likely to need them. Every section has code, and every code sample is followed by what it prints or what the compiler says. The text follows the GCC 14 manual, chapters Function Attributes, Variable Attributes, Type Attributes and Other Built-in Functions, and notes where Clang 18 differs. Examples target x86-64 Linux unless a section says otherwise.

How to read this guide

You can read it front to back, or jump. If you write libraries, start with the function attributes. If you write low-level code, read the variable, type and section material. If you maintain a code base that builds with more than one compiler, read the portability section before you add a single attribute, because it prevents the mess most projects end up with. The last sections are a decision table, a list of mistakes that cost real debugging hours, and the FAQ.

One principle runs through all of it: an attribute is a promise or a request, and the two have different failure modes. A request such as noinline or cold can be wrong and cost you some speed. A promise such as noreturn, const or nonnull can be wrong and cost you correctness, because the optimizer will rely on it. Treat promises with the care you would give undefined behavior, since a false promise is exactly that.

Syntax: where attributes go and how they are spelled

GCC attributes use a double-parenthesis form that the preprocessor treats as an ordinary token sequence, so you can hide it behind a macro on compilers that lack it:

c
int square(int x) __attribute__((const));

The attribute list may sit after the declarator, before the declaration, or between the declaration specifiers, and for functions the safest spot is at the end of the declaration or immediately before the return type. Several attributes can share one pair of outer parentheses, separated by commas:

c
__attribute__((noreturn, cold)) void die(const char *msg);

Names can be written with underscores on both sides, __noreturn__, which prevents a clash if a header happens to #define noreturn. System headers always use the underscored forms for that reason, and you should too in any header that other people include.

There are two newer spellings. C23, supported by GCC from version 13, standardizes the double-bracket syntax and the attributes [[noreturn]], [[nodiscard]], [[deprecated]], [[maybe_unused]] and [[fallthrough]]. C++11 had the same syntax earlier. GCC also accepts any of its own attributes in that syntax under the gnu namespace: [[gnu::always_inline]], [[gnu::cold]]. The bracket form attaches to the entity that follows it, and a position error is diagnosed more clearly than a misplaced __attribute__.

attr_syntax.cc
#include <stdio.h>
#include <stdlib.h>

[[noreturn]] static void fail(const char *why)
{
    fprintf(stderr, "error: %s\n", why);
    exit(2);
}

[[gnu::cold]] static void report(int code)
{
    fprintf(stderr, "code %d\n", code);
}

int main(void)
{
    report(7);
    fail("demo");
}

Compile it with gcc -std=c23 attr_syntax.c on GCC 13 or later. Running it prints to standard error and exits with status 2:

Text
code 7
error: demo

On GCC 12 and earlier, use -std=gnu2x for the bracket forms, and expect that [[noreturn]] before the declaration works but some of the newer standard attributes do not.

Detecting what the compiler supports

Never test the compiler version number to decide whether an attribute exists. Version numbers drift between GCC, Clang and vendor forks that claim to be GCC. Use the feature tests instead. __has_attribute(name) is available in GCC from version 5 and in Clang, and __has_builtin(name) from GCC 10. __has_c_attribute(name) tests the bracket form from GCC 11 and in C23.

has_attr.cc
#include <stdio.h>

int main(void)
{
#if defined(__has_attribute)
#if __has_attribute(cold)
    puts("cold: yes");
#endif
#if __has_attribute(no_such_attribute)
    puts("no_such_attribute: yes");
#else
    puts("no_such_attribute: no");
#endif
#endif
#if defined(__has_builtin) && __has_builtin(__builtin_popcount)
    puts("popcount: yes");
#endif
    return 0;
}
Text
cold: yes
no_such_attribute: no
popcount: yes

Because __has_attribute is itself missing on very old compilers, guard it with defined(__has_attribute) and nest the check, as above; a bare #if __has_attribute(x) is a syntax error where the operator does not exist.

Portable macros: the header every project should have

Wrapping each attribute in a macro does three things: it documents intent in one place, it lets the project compile on a compiler that lacks the attribute, and it gives you one line to change when the spelling moves. A small header covers the attributes used in this guide:

attrs.hc
#ifndef ATTRS_H
#define ATTRS_H

#if defined(__has_attribute)
#define HAS_ATTR(x) __has_attribute(x)
#else
#define HAS_ATTR(x) 0
#endif

#if HAS_ATTR(noreturn)
#define NORETURN __attribute__((__noreturn__))
#else
#define NORETURN
#endif

#if HAS_ATTR(format)
#define PRINTF_LIKE(fmt, first) __attribute__((__format__(__printf__, fmt, first)))
#else
#define PRINTF_LIKE(fmt, first)
#endif

#if HAS_ATTR(warn_unused_result)
#define MUST_CHECK __attribute__((__warn_unused_result__))
#else
#define MUST_CHECK
#endif

#if HAS_ATTR(nonnull)
#define NONNULL(...) __attribute__((__nonnull__(__VA_ARGS__)))
#else
#define NONNULL(...)
#endif

#if HAS_ATTR(unused)
#define MAYBE_UNUSED __attribute__((__unused__))
#else
#define MAYBE_UNUSED
#endif

#if defined(__GNUC__) || defined(__clang__)
#define LIKELY(x)   __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)
#else
#define LIKELY(x)   (x)
#define UNLIKELY(x) (x)
#endif

#endif

The rest of the guide uses these names when they make an example shorter, and spells out the raw attribute where the details matter. The Linux kernel has a larger version of the same file in include/linux/compiler_attributes.h, and it is worth reading as a catalog.

Function attributes that describe behavior

These attributes tell the optimizer facts about what a function does. They are promises. Make them only when you can prove them.

noreturn

noreturn says the function never returns to its caller: it calls exit, abort, longjmp, or loops forever. The compiler uses it to drop code after the call and to avoid warnings about missing return values. Getting it wrong, a function that sometimes returns, is undefined behavior; the compiler will not generate a return path and execution falls into whatever follows.

noreturn_demo.cc
#include <stdio.h>
#include <stdlib.h>

__attribute__((noreturn)) void die(const char *msg)
{
    fprintf(stderr, "fatal: %s\n", msg);
    exit(1);
}

int parse(const char *s)
{
    if (!s)
        die("null input");
    return (int)strtol(s, NULL, 10);
}

int main(void)
{
    printf("%d\n", parse("41") + 1);
    return 0;
}
Text
42

Because die is noreturn, GCC does not warn that parse might reach the end without a return in the null branch, and it can place the die call out of line as a cold branch.

const and pure

const marks a function whose result depends only on its arguments, with no reads of global memory, no pointer dereferencing of mutable state and no side effects. pure is weaker: the function may read global memory but has no side effects. Both allow the compiler to fold repeated calls into one and to hoist calls out of loops.

pure_const.cc
#include <stdio.h>
#include <string.h>

__attribute__((const)) static int square(int x)
{
    return x * x;
}

__attribute__((pure)) static size_t twice_len(const char *s)
{
    return 2 * strlen(s);
}

int main(void)
{
    int a = square(7);
    int b = square(7);          /* may be evaluated once */
    printf("%d %d %zu\n", a, b, twice_len("abc"));
    return 0;
}
Text
49 49 6

A function that reads through a pointer cannot be const, because the pointed-to data is memory the result depends on. Mark it pure. A function that writes through a pointer or sets errno can be neither. Marking strlen-like functions pure is correct; marking a function that logs const is a bug the optimizer will turn into silently missing log lines.

malloc, alloc_size and returns_nonnull

malloc says the returned pointer does not alias any other pointer live at that moment, which lets the compiler keep loads and stores through it apart from others. alloc_size(n) says argument n is the size in bytes of the object returned, which powers -Walloc-size, __builtin_object_size and fortify checks. returns_nonnull promises the result is never null.

alloc.cc
#include <stdlib.h>
#include <string.h>

__attribute__((malloc, alloc_size(1), returns_nonnull))
static void *xalloc(size_t n)
{
    void *p = malloc(n ? n : 1);
    if (!p)
        abort();
    return p;
}

int main(void)
{
    char *buf = xalloc(16);
    memset(buf, 0, 16);
    free(buf);
    return 0;
}

GCC 11 added the form malloc(deallocator, ptr_index), for example __attribute__((malloc(free, 1))), which lets -Wmismatched-dealloc catch a pointer from xalloc passed to the wrong free function. Use it whenever a project has custom allocators.

nonnull and warn_unused_result

nonnull marks pointer parameters that must not be null. With no arguments it applies to all pointer parameters; with numbers it picks them by position, counting from 1. -Wnonnull warns on a constant null argument at the call site, and the optimizer is allowed to delete a later null check on that parameter, since a null would already have been undefined behavior.

warn_unused_result makes the compiler warn if a caller discards the return value, which suits functions whose failure must be handled.

checks.cc
#include <stdio.h>

__attribute__((nonnull(1), warn_unused_result))
int open_config(const char *path);

int open_config(const char *path)
{
    return path[0] == '/' ? 0 : -1;
}

int main(void)
{
    open_config("/etc/app.conf");
    open_config(NULL);
    return 0;
}

Compiling with gcc -Wall -c checks.c reports, abridged:

Text
checks.c: In function 'main':
checks.c:14:5: warning: ignoring return value of 'open_config' declared with attribute 'warn_unused_result' [-Wunused-result]
checks.c:15:5: warning: argument 1 null where non-null expected [-Wnonnull]

Casting the result to void does not silence warn_unused_result in GCC, which is a deliberate difference from [[nodiscard]] in C23 and C++. The portable way to say "I know" is to assign to a variable and mark that (void)v.

format and sentinel

format(archetype, string-index, first-to-check) makes the compiler check printf-style, scanf-style, strftime-style or gnu_printf arguments against the format string at every call site. Put it on every logging function you write. Without it, a bad format string in a rarely taken error path is a run-time bug that shows up in production.

logfmt.cc
#include <stdarg.h>
#include <stdio.h>

__attribute__((format(printf, 1, 2)))
void logmsg(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);
}

int main(void)
{
    logmsg("count=%d name=%s\n", 3, "alpha");
    logmsg("count=%d\n", "oops");
    return 0;
}
Text
logfmt.c: In function 'main':
logfmt.c:17:21: warning: format '%d' expects argument of type 'int', but argument 2 has type 'char *' [-Wformat=]

Because logmsg has the attribute, -Wformat (included in -Wall) checks it like printf. The variant format_arg marks a function that returns a translated version of a format string, which matters for gettext-style wrappers. sentinel marks variadic functions that end with a NULL argument list terminator, such as execl, and warns if the terminator is missing.

deprecated and unavailable-style warnings

deprecated makes any use of the function or type emit a warning, and takes an optional message. It is the standard way to retire an API without breaking the build immediately.

dep.cc
__attribute__((deprecated("use new_api() instead")))
int old_api(void) { return 1; }

int new_api(void) { return 2; }

int main(void)
{
    return old_api();
}
Text
dep.c: In function 'main':
dep.c:8:12: warning: 'old_api' is deprecated: use new_api() instead [-Wdeprecated-declarations]

GCC 12 added __attribute__((unavailable)) as a Clang-compatible way to make use an error, and -Wno-deprecated-declarations silences the deprecation warnings you accept for a while.

Function attributes that steer code generation

These are requests, and the compiler may ignore them in odd cases. Use them for performance and layout.

always_inline, noinline, flatten

always_inline forces inlining, and the compiler errors if it cannot comply; it must be paired with inline in C. noinline forbids it, which is useful for functions you want to appear in a profile or a backtrace. flatten asks GCC to inline every call inside the marked function, recursively where possible, useful for a hot dispatcher.

inl.cc
static inline __attribute__((always_inline)) int clamp255(int x)
{
    return x < 0 ? 0 : (x > 255 ? 255 : x);
}

__attribute__((noinline)) int pixel(int v)
{
    return clamp255(v * 2);
}

hot, cold and the section they choose

cold tells the compiler the function is rarely run: it optimizes for size, treats calls to it as unlikely, and puts it in .text.unlikely. hot pushes the other way and places it in .text.hot. Apply cold to error handlers and hot to inner kernels.

noipa, noclone and optimize

noipa (GCC 8) disables inter-procedural optimization for a function: no inlining, cloning or constant propagation into it. It is the right tool for a benchmark function the compiler must not fold away, and for test fixtures. noclone blocks only cloning. optimize("O3") and optimize("no-tree-vectorize") set optimization options for one function, but the GCC manual says it is for debugging only: it can inhibit inlining and the resulting behavior is not guaranteed across versions. Prefer a separate translation unit with its own flags.

target, target_clones and ifunc

target("avx2") compiles one function with an instruction set extension that the rest of the file lacks, so you can use AVX2 code behind a run-time CPU check without building the whole program with -mavx2. target_clones("avx2","default") generates multiple versions and picks one at load time through an ifunc resolver. The same machinery is exposed directly as ifunc.

clones.cc
#include <stdio.h>

__attribute__((target_clones("avx2", "default")))
int sum(const int *a, int n)
{
    int s = 0;
    for (int i = 0; i < n; i++)
        s += a[i];
    return s;
}

int main(void)
{
    int v[8] = {1, 2, 3, 4, 5, 6, 7, 8};
    printf("%d\n", sum(v, 8));
    return 0;
}
Text
36

The output is the same on any CPU, only the code that computes it differs. Both attributes require a target with the dynamic loader's support for indirect functions, which means glibc on Linux, and they do not work on bare-metal targets.

constructor and destructor

constructor runs a function before main, and destructor after main returns or exit is called. Both take an optional priority from 101 to 65535, where lower numbers run first; priorities 0 to 100 are reserved for the implementation. They are how shared libraries initialize themselves and how some frameworks register plugins.

ctor.cc
#include <stdio.h>

__attribute__((constructor(101))) static void early(void) { puts("early"); }
__attribute__((constructor))     static void normal(void) { puts("normal"); }
__attribute__((destructor))      static void bye(void)    { puts("bye"); }

int main(void)
{
    puts("main");
    return 0;
}
Text
early
normal
main
bye

A dedicated post in this series covers startup order and pitfalls in depth. The one rule worth stating here: do not rely on stdio or malloc state inside a constructor in a shared library that the dynamic loader initializes early.

Function attributes for symbols and sections

visibility, weak, alias

visibility("hidden") keeps a symbol out of a shared object's dynamic symbol table, shrinking the library and allowing the compiler to assume calls are local, which turns PLT calls into direct ones. weak lets a definition be overridden by a strong one elsewhere. alias("target") makes one symbol another name for an existing function in the same translation unit.

sym.cc
void impl(void) {}
void api(void) __attribute__((alias("impl")));

__attribute__((weak)) int config_level(void) { return 1; }
__attribute__((visibility("hidden"))) int internal_helper(void) { return 2; }

Inspect the object with nm to see W for the weak symbol and both names for the alias:

Text
0000000000000000 T api
0000000000000000 T impl
0000000000000006 W config_level
0000000000000010 T internal_helper

Hidden visibility appears in readelf -s as HIDDEN and not in nm's letter. The -fvisibility=hidden compile flag makes hidden the default for a whole library, with visibility("default") marking the exported API, which is the recommended pattern for shared libraries.

section

section("name") places a function or variable in a named section, and combined with a linker script it controls exactly where code lands in memory. Embedded programs use it for code that must run from RAM, and kernels use it for tables of handlers.

sec.cc
__attribute__((section(".ramfunc"), noinline))
int fast_add(int a, int b)
{
    return a + b;
}

objdump -h sec.o lists .ramfunc as its own section, and the linker script decides its load and run addresses. Add used when the only reference to an object is from the linker script, so garbage collection does not drop it.

used and unused

used tells the compiler to emit a static object even when it sees no reference; unused suppresses the warning about an unreferenced variable or parameter. They are opposites in effect and often confused. Use used for tables referenced from inline assembly or a linker script, and unused for parameters that exist for interface reasons.

Statement and label attributes

fallthrough marks an intentional fall-through from one case to the next so -Wimplicit-fallthrough stays quiet where it should and fires where it should not:

fall.cc
#include <stdio.h>

void describe(int level)
{
    switch (level) {
    case 2:
        puts("level two");
        __attribute__((fallthrough));
    case 1:
        puts("level one");
        break;
    default:
        break;
    }
}

int main(void)
{
    describe(2);
    return 0;
}
Text
level two
level one

In C23 you write [[fallthrough]];. -Wimplicit-fallthrough is part of -Wextra. Also in this family: hot and cold on labels, and unused on labels, which silences an unused-label warning in generated code.

Variable attributes

aligned and packed

aligned(n) raises the alignment of a variable, a field or a type to n bytes, where n is a power of two. packed removes padding from a struct or union, or from one field. They solve opposite problems: aligned for SIMD loads, DMA buffers and cache-line separation, packed for matching a wire format or a file layout.

layout.cc
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>

struct normal { uint8_t tag; uint32_t value; };
struct tight  { uint8_t tag; uint32_t value; } __attribute__((packed));

static char buf[64] __attribute__((aligned(64)));

int main(void)
{
    printf("normal: size=%zu value@%zu\n", sizeof(struct normal), offsetof(struct normal, value));
    printf("tight:  size=%zu value@%zu\n", sizeof(struct tight),  offsetof(struct tight, value));
    printf("buf aligned to 64: %d\n", (int)(((uintptr_t)buf & 63) == 0));
    return 0;
}
Text
normal: size=8 value@4
tight:  size=5 value@1
buf aligned to 64: 1

Packed fields are misaligned, and taking their address yields a pointer the compiler no longer knows is aligned, which GCC warns about under -Waddress-of-packed-member. On targets that fault on unaligned access it is a real bug. The usual safe pattern is to memcpy the field out. Separate posts in this series cover packing and alignment in depth.

cleanup, mode and vector_size

cleanup(fn) runs fn on a variable's address when it goes out of scope, which gives C a destructor-like mechanism used for locks, file descriptors and heap memory. mode(...) selects a machine mode, mostly historical. vector_size(n) declares a SIMD vector type of n bytes, on which GCC lets you use ordinary operators.

vec.cc
#include <stdio.h>

typedef int v4si __attribute__((vector_size(16)));

int main(void)
{
    v4si a = {1, 2, 3, 4};
    v4si b = {10, 20, 30, 40};
    v4si c = a + b;
    printf("%d %d %d %d\n", c[0], c[1], c[2], c[3]);
    return 0;
}
Text
11 22 33 44

The compiler lowers the addition to one paddd on x86-64 or to scalar operations when the target has no vector unit. This is the portable alternative to intrinsics for simple lane-wise math.

may_alias and transparent_union

may_alias exempts a type from strict aliasing rules, which is how the SIMD vector types and some network buffer types stay safe. transparent_union lets a function accept any member type of a union without a cast, and appears in wait-style interfaces.

Type attributes and enum helpers

packed, aligned and may_alias also apply to types. deprecated on a type flags every use, and designated_init (GCC 5) forces callers to use designated initializers for a struct, so reordering its fields never silently changes meaning. flag_enum is Clang-only. __attribute__((mode(byte))) and friends select integer widths on an old API, and you will rarely need them in new code.

The builtins

A builtin is an operation the compiler treats as part of the language. Most have a library fallback, so code that uses them still links on a target without a special instruction.

Branch hints and unreachable code

__builtin_expect(expr, value) tells the compiler that expr is likely to equal value. The usual wrapper is the LIKELY and UNLIKELY macros from the header above, using !! to normalize to 0 or 1. GCC 9 added __builtin_expect_with_probability(expr, value, prob) for a stated probability between 0.0 and 1.0.

__builtin_unreachable() tells the compiler control cannot get here, so it may delete the path; if control does get there the behavior is undefined. It is useful after a switch that covers every value, and dangerous everywhere else. __builtin_trap() generates an instruction that faults, such as ud2 on x86-64, which is the safe form of "this cannot happen".

branch.cc
#include <stdio.h>

#define UNLIKELY(x) __builtin_expect(!!(x), 0)

int parse_digit(char c)
{
    if (UNLIKELY(c < '0' || c > '9'))
        return -1;
    return c - '0';
}

int main(void)
{
    printf("%d %d\n", parse_digit('7'), parse_digit('x'));
    return 0;
}
Text
7 -1

GCC lays the error return out of line so the common path falls through. C++20 spells the same hint [[likely]] and [[unlikely]], and the next section ties them together.

Bit manipulation

The family __builtin_popcount, __builtin_clz, __builtin_ctz, __builtin_ffs, __builtin_parity and __builtin_bswap16/32/64 maps to single instructions on CPUs that have them and to short sequences elsewhere. Each exists in l and ll forms for unsigned long and unsigned long long. clz and ctz are undefined for an argument of zero, which is the most common source of bugs in code that uses them.

bits.cc
#include <stdio.h>

int main(void)
{
    unsigned x = 0x00F0u;
    printf("popcount=%d clz=%d ctz=%d bswap=0x%08x\n",
           __builtin_popcount(x), __builtin_clz(x), __builtin_ctz(x),
           __builtin_bswap32(0x11223344u));
    return 0;
}
Text
popcount=4 clz=24 ctz=4 bswap=0x44332211

0x00F0 has four bits set, 24 leading zeros in a 32-bit unsigned and four trailing zeros. Compile with -mpopcnt or -march=x86-64-v2 to turn popcount into one popcnt instruction; without it GCC calls a small helper in libgcc.

Overflow-checked arithmetic

__builtin_add_overflow(a, b, &result) and the sub and mul forms compute the mathematically exact result, store the wrapped value into *result, and return nonzero if it did not fit. The operands may be of different types. They are the right way to write overflow-safe size calculations before an allocation.

ovf.cc
#include <stdio.h>
#include <stdint.h>

int main(void)
{
    uint8_t out;
    int bad = __builtin_add_overflow((uint8_t)200, (uint8_t)100, &out);
    printf("overflow=%d wrapped=%u\n", bad, out);
    return 0;
}
Text
overflow=1 wrapped=44

200 plus 100 is 300, which wraps to 44 modulo 256. C23 standardizes ckd_add, ckd_sub and ckd_mul in <stdckdint.h>, available from GCC 14.

Compile-time introspection

__builtin_constant_p(expr) returns 1 if the compiler can prove expr is a constant after optimization, which lets a macro pick a fast path for literals. __builtin_types_compatible_p(t1, t2) compares types, and __builtin_choose_expr(const_expr, a, b) selects an expression at compile time without evaluating the other. Together they were the way to write type-generic macros before _Generic. __builtin_offsetof(type, member) is what offsetof expands to.

Memory and prefetch

__builtin_prefetch(addr, rw, locality) hints that memory will be used soon: rw is 0 for read and 1 for write, and locality is 0 to 3. It helps pointer-chasing loops when you know the next address early, and hurts when you guess wrong, so measure. __builtin_assume_aligned(p, n) tells the compiler a pointer is n-aligned and returns it, so vector loads can be aligned. __builtin_memcpy, __builtin_strlen and friends are what the standard names usually compile to, and they let the compiler fold calls with constant arguments.

Introspection of the caller

__builtin_return_address(0) and __builtin_frame_address(0) read the return address and frame of the current function, which backtrace and tracing code uses. Nonzero levels read further up the stack and are unreliable without frame pointers. __builtin_FILE(), __builtin_LINE() and __builtin_FUNCTION() return the location of the call, handy as default arguments in C++ and in macros.

Atomics

The __atomic_* builtins implement the C11 memory model on any type of 1, 2, 4, 8 or 16 bytes where the hardware supports it: __atomic_load_n, __atomic_store_n, __atomic_exchange_n, __atomic_compare_exchange_n, __atomic_fetch_add and a fence. Each takes a memory order such as __ATOMIC_RELAXED or __ATOMIC_SEQ_CST. The older __sync_* builtins predate the model, imply a full barrier and should not be used in new code. Prefer <stdatomic.h> unless you target a compiler without it.

atom.cc
#include <stdio.h>

static int counter;

int main(void)
{
    __atomic_fetch_add(&counter, 5, __ATOMIC_RELAXED);
    __atomic_fetch_add(&counter, 2, __ATOMIC_RELAXED);
    printf("%d\n", __atomic_load_n(&counter, __ATOMIC_ACQUIRE));
    return 0;
}
Text
7

Security builtins

__builtin_object_size(ptr, type) returns the size of the object a pointer refers to when known at compile time, or (size_t)-1. It underlies _FORTIFY_SOURCE and the __builtin___memcpy_chk family, which glibc enables with -D_FORTIFY_SOURCE=2 or =3 plus optimization. __builtin_speculation_safe_value (GCC 9) hardens against speculative-execution reads.

A worked example: a small library that uses them well

Reading about attributes one at a time hides how they combine. The module below is a tiny buffer library of the kind a C project grows in its first year. It uses the portable macros from the header earlier, and each annotation is there because it prevents a specific mistake.

buf.hc
#ifndef BUF_H
#define BUF_H

#include <stddef.h>
#include "attrs.h"

struct buf {
    unsigned char *data;
    size_t len;
    size_t cap;
};

void buf_init(struct buf *b) NONNULL(1);
MUST_CHECK int buf_append(struct buf *b, const void *src, size_t n) NONNULL(1);
MUST_CHECK int buf_appendf(struct buf *b, const char *fmt, ...)
    PRINTF_LIKE(2, 3) NONNULL(1, 2);
NORETURN void buf_die(const char *msg) NONNULL(1);
void buf_free(struct buf *b) NONNULL(1);

#endif

The header carries all the checks, since callers see only declarations. buf_append and buf_appendf return an error code that callers must look at, so they are MUST_CHECK. buf_appendf takes a printf-style format, so it gets PRINTF_LIKE(2, 3): the format string is parameter 2 and the variadic arguments start at 3. buf_die never returns. The implementation uses builtins where they matter:

buf.cc
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "buf.h"

void buf_init(struct buf *b)
{
    b->data = NULL;
    b->len = 0;
    b->cap = 0;
}

static int grow(struct buf *b, size_t need)
{
    size_t total;
    if (__builtin_add_overflow(b->len, need, &total))
        return -1;
    if (total <= b->cap)
        return 0;
    size_t newcap = b->cap ? b->cap : 16;
    while (newcap < total) {
        if (__builtin_mul_overflow(newcap, (size_t)2, &newcap))
            return -1;
    }
    unsigned char *p = realloc(b->data, newcap);
    if (UNLIKELY(!p))
        return -1;
    b->data = p;
    b->cap = newcap;
    return 0;
}

int buf_append(struct buf *b, const void *src, size_t n)
{
    if (grow(b, n) != 0)
        return -1;
    memcpy(b->data + b->len, src, n);
    b->len += n;
    return 0;
}

int buf_appendf(struct buf *b, const char *fmt, ...)
{
    char tmp[256];
    va_list ap;
    va_start(ap, fmt);
    int n = vsnprintf(tmp, sizeof tmp, fmt, ap);
    va_end(ap);
    if (n < 0 || (size_t)n >= sizeof tmp)
        return -1;
    return buf_append(b, tmp, (size_t)n);
}

void buf_die(const char *msg)
{
    fprintf(stderr, "buf: %s\n", msg);
    exit(1);
}

void buf_free(struct buf *b)
{
    free(b->data);
    buf_init(b);
}

Two builtins pull their weight. __builtin_add_overflow guards the size computation, so a huge n cannot wrap len + n to a small number and cause a heap overflow. __builtin_mul_overflow guards the doubling loop for the same reason. UNLIKELY marks the allocation failure so the compiler moves it out of the hot path.

A caller shows what the attributes catch:

use.cc
#include <stdio.h>
#include "buf.h"

int main(void)
{
    struct buf b;
    buf_init(&b);
    if (buf_appendf(&b, "id=%d name=%s\n", 7, "node") != 0)
        buf_die("append failed");
    buf_append(&b, "!", 1);
    fwrite(b.data, 1, b.len, stdout);
    buf_free(&b);
    return 0;
}

Compiled with gcc -Wall -Wextra -c use.c, the discarded result of the second buf_append call is reported, because the declaration says the result must be checked:

Text
use.c: In function 'main':
use.c:11:5: warning: ignoring return value of 'buf_append' declared with attribute 'warn_unused_result' [-Wunused-result]

The program, once that line is fixed, prints the formatted line and the exclamation mark. Each annotation came from a bug the team would otherwise find in review or in production: unchecked failures, format mismatches, null arguments and silent overflow in size arithmetic. That is the pattern for using this feature set well. Add an attribute where a class of mistake is cheap to prevent, not to decorate.

Seeing what the compiler did with an attribute

An attribute that does nothing is common, and the way to find out is to look. For promise attributes, compile a small function twice, with and without the annotation, and compare the assembly:

fold.cc
__attribute__((const)) int cube(int x);

int use_twice(int v)
{
    return cube(v) + cube(v);
}
Shell
gcc -O2 -S -o - fold.c | sed -n '/use_twice:/,/ret/p'
Text
use_twice:
	subq	$8, %rsp
	call	cube
	addq	$8, %rsp
	addl	%eax, %eax
	ret

With const, the compiler calls cube once and doubles the result with addl %eax, %eax. Remove the attribute and the output contains two call cube instructions, since the function might have side effects. The exact instructions depend on the version and flags, but one call versus two is the signal. For layout attributes use nm, readelf -S and objdump -h. For cold and hot, look at section names. For format and nonnull, the proof is a warning, so write a failing call on purpose and check that the compiler complains, then delete it.

Attributes, LTO and visibility

Link-time optimization changes how some attributes behave, because the optimizer then sees callers in other files. A const function in one file and its calls in another benefit from the promise only with LTO, or when the attribute is on the header declaration the callers include, which is the recommended place. A function marked noinline stays out of line under LTO as well, and used keeps a symbol that the linker's garbage collection would otherwise drop. visibility("hidden") combined with LTO lets the compiler treat the function as internal to the shared object, so it can inline and clone it freely, which is why -fvisibility=hidden plus an explicit export macro is the standard recipe for a shared library.

A related caution concerns weak and LTO. An overridable weak function cannot be inlined into callers, since a strong definition elsewhere may replace it, so a weak default costs a call. If the override mechanism is not needed in a given build, define the function strongly under a macro.

What changes between GCC versions

Attribute and builtin availability grows with each release, so name the version in your documentation and test it. Examples from the manual: __has_attribute arrived in GCC 5, noipa in GCC 8, malloc with a deallocator argument and access in GCC 10 and 11, __has_builtin in GCC 10, the C23 bracket attributes in GCC 10 through 13 as they were added, __builtin_assume is Clang only, and ckd_add in GCC 14. When you depend on a newer feature, guard it with the feature test and provide a fallback, because an enterprise build machine may run an older compiler than your laptop.

How the C library and the kernel use them

You do not have to invent a style, because two large code bases show how it looks at scale. The GNU C Library's headers wrap attributes in macros from <sys/cdefs.h>: __THROW for functions that do not throw in C++, __nonnull((1, 2)) for pointer parameters, __wur for warn_unused_result, __attribute_malloc__, __attribute_pure__ and __attribute_const__, and __attr_access for the access attribute. When you read a prototype such as read or strchr in the system headers, you are reading the same attributes this guide describes, applied by people who had to be right across every architecture. For example, strlen is marked pure and nonnull, which is why the compiler is free to fold strlen("abc") to 3 and to hoist a strlen call out of a loop in which the string does not change.

The Linux kernel keeps its portable macros in include/linux/compiler_attributes.h and include/linux/compiler.h. It defines __always_inline, __noreturn, __cold, __printf(a, b) for the format attribute, __packed, __aligned(x), __section(s), __used, __maybe_unused, __must_check and fallthrough, and it feature-tests with __has_attribute for each. Its likely() and unlikely() macros wrap __builtin_expect. If you want a tested list of attributes that matter in systems code, that header is the shortest one available, and each macro has a comment explaining the reason.

A routine for adding an attribute safely

Teams get into trouble by adding attributes in bulk. A small routine avoids it. First, decide whether the attribute is a check, a request or a promise. Checks are low-risk and should be added widely. Requests deserve a measurement. Promises need a proof, which for const and pure means reading the function and every function it calls, and for nonnull means grepping the callers. Second, put the attribute in the header declaration so every call site sees it. Third, write a failing case on purpose: a call that violates the attribute, to confirm the compiler diagnoses it, and a check on the assembly if the attribute is supposed to change code. Fourth, build with both GCC and Clang in CI, and with -Wall -Wextra, so attribute misuse is reported on both. Fifth, record why in a comment, since "why is this noinline" is a question nobody can answer six months later without one.

When a promise turns out to be wrong, the symptom is almost always a bug that disappears at -O0. If an optimized build misbehaves and a debug build does not, bisect the attributes on the functions involved by removing them from a header one at a time. A const or noreturn that was true when written and became false after a refactor is the classic cause. Sanitizers do not know about these promises, so a review pass over the attributes in a header, each time its functions change, is the only defense.

Using the same attributes from C++

Most of what this guide describes applies to C++ unchanged, since GCC implements one set of attributes for both front ends. The differences come from the language: [[nodiscard]] and [[likely]] are standard since C++17 and C++20, constexpr and consteval replace several uses of __builtin_constant_p, and std::bit_cast, std::popcount and std::countl_zero from C++20 <bit> replace the bit builtins with defined behavior for zero. Prefer the standard forms in new C++ code and keep the __builtin_ calls for code that must build as C.

Choosing the right tool

You want to...UseKind
Stop warnings about a function that never returnsnoreturnPromise
Let the compiler fold repeated callsconst or purePromise
Catch format-string mistakes at compile timeformat(printf, n, m)Check
Force callers to check a resultwarn_unused_resultCheck
Keep a function out of the hot instruction streamcoldRequest
Put code or data in a named regionsection("name")Directive
Match a wire formatpackedLayout
Align to a cache line or SIMD widthaligned(n)Layout
Count bits__builtin_popcount and clz/ctzBuiltin
Detect overflow__builtin_add_overflowBuiltin
Hint a likely branch__builtin_expectHint
Release a resource at scope exitcleanup(fn)Directive
Pick an implementation per CPUtarget_clonesDispatch

Mistakes that cost real time

  • **const on a function that reads memory.** The optimizer caches the result and your function returns stale data. If it reads anything but its arguments, use pure, or none.

  • **noreturn on a function with a return path.** A rarely taken branch returns, execution falls through into the next function, and the crash is nowhere near the cause.

  • **__builtin_unreachable() as a comment.** It is an instruction to the optimizer, not documentation. If the path is reachable, you get undefined behavior; use an assert plus __builtin_trap() in builds that should fail loudly.

  • **clz and ctz of zero.** Undefined. Check for zero first, or use the C23 stdc_leading_zeros family on GCC 14.

  • **packed structs and pointers.** A pointer to a packed field may be misaligned and fault on strict-alignment CPUs.

  • Attributes on the definition only. format, nonnull and warn_unused_result must be visible at the call sites, so put them on the declaration in the header.

  • **optimize as a tuning tool.** GCC documents it as for debugging, and it can silently disable inlining.

  • Forgetting that Clang differs. __attribute__((const)) is the same, but a few GCC attributes such as optimize and flatten have different or no support. Test builds with both compilers if you ship to both.

When not to use these features

If a project must compile with MSVC or a strict ISO C compiler, keep the attributes behind macros as shown, and expect no benefit there. Do not mark functions hot, cold or flatten without a profile; the compiler's own heuristics are usually better, and an annotation that was right in 2024 can be wrong after a refactor. Prefer standard features when they exist: _Generic over __builtin_choose_expr, <stdatomic.h> over __atomic, [[nodiscard]] over warn_unused_result in C23 code, alignas over aligned.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.