GNU C `__attribute__` Guide

Common GNU C `__attribute__` usage patterns and examples.

Syntax

1
__attribute__((attribute-list))

attribute-list is a comma-separated list of attributes.

Common Attributes

packed

Removes default structure padding and minimizes alignment gaps.

1
2
3
4
struct __attribute__((packed)) packed_str {
    uint8_t x;
    uint16_t y;
};

Use with care: unaligned access can reduce performance or cause faults on some architectures.

aligned(n)

Forces object alignment to n bytes.

1
int buf[16] __attribute__((aligned(64)));

section("name")

Places variable/function into a custom linker section.

1
const char fw_ver[] __attribute__((section(".fwinfo"))) = "1.0.0";

unused

Suppresses unused warnings.

1
static void helper(void) __attribute__((unused));

weak

Declares weak symbol (can be overridden by strong definition).

1
void board_init(void) __attribute__((weak));

noreturn

Marks function that never returns.

1
void fatal_error(void) __attribute__((noreturn));

Notes

  • __attribute__ is compiler-specific (GCC/Clang compatible in many cases).
  • Prefer macros for portability when targeting multiple compilers.
记录并分享
Built with Hugo
Theme Stack designed by Jimmy