跳转到内容
新建笔记

GCC编译器扩展机制 - 表格汇总

属性语法用途示例
section__attribute__((section("name")))指定存储段__attribute__((section(".ccmram"))) int var;
aligned__attribute__((aligned(n)))对齐到n字节__attribute__((aligned(32))) uint8_t buf[1024];
packed__attribute__((packed))取消对齐,紧凑存储struct __attribute__((packed)) { uint8_t a; uint32_t b; };
weak__attribute__((weak))弱符号,可被覆盖__attribute__((weak)) void handler(void);
alias__attribute__((alias("name")))创建别名void f(void) __attribute__((alias("g")));
used__attribute__((used))防止被优化掉__attribute__((used)) static int keep_me;
unused__attribute__((unused))消除未使用警告__attribute__((unused)) int param;
noinit__attribute__((noinit))不初始化__attribute__((noinit)) uint8_t big_buf[65536];
constructor__attribute__((constructor))main前执行__attribute__((constructor)) void init(void);
destructor__attribute__((destructor))main后执行__attribute__((destructor)) void cleanup(void);
interrupt__attribute__((interrupt))中断处理函数__attribute__((interrupt)) void ISR(void);
naked__attribute__((naked))无函数序言/尾声__attribute__((naked)) void asm_func(void);
noreturn__attribute__((noreturn))函数不返回__attribute__((noreturn)) void reset(void);
optimize__attribute__((optimize("O3")))指定优化级别__attribute__((optimize("O0"))) void debug(void);
always_inline__attribute__((always_inline))强制内联__attribute__((always_inline)) static inline void fast(void);
noinline__attribute__((noinline))禁止内联__attribute__((noinline)) void no_inline(void);
pure__attribute__((pure))纯函数,无副作用__attribute__((pure)) int calc(int x);
const__attribute__((const))只依赖参数的函数__attribute__((const)) int square(int x);
hot__attribute__((hot))热点代码__attribute__((hot)) void frequent(void);
cold__attribute__((cold))冷代码__attribute__((cold)) void rare(void);
deprecated__attribute__((deprecated))标记为过时__attribute__((deprecated)) void old_api(void);
format__attribute__((format(printf,1,2)))格式检查__attribute__((format(printf,1,2))) void log(char *fmt, ...);

二、内置函数 - 位操作

跳转到“二、内置函数 - 位操作”
函数返回值功能示例
__builtin_clz(x)int前导零个数(32位)int lz = __builtin_clz(0x00F00000); // 8
__builtin_clzll(x)int前导零个数(64位)int lz = __builtin_clzll(0x00F0000000000000LL);
__builtin_ctz(x)int尾随零个数(32位)int tz = __builtin_ctz(0x00000F00); // 8
__builtin_ctzll(x)int尾随零个数(64位)int tz = __builtin_ctzll(0x00000F0000000000LL);
__builtin_popcount(x)int1的个数(32位)int cnt = __builtin_popcount(0xFF); // 8
__builtin_popcountll(x)int1的个数(64位)int cnt = __builtin_popcountll(0xFFLL);
__builtin_parity(x)int奇偶性(32位)int p = __builtin_parity(0x11); // 0(偶)
__builtin_parityll(x)int奇偶性(64位)int p = __builtin_parityll(0x11LL);
__builtin_ffs(x)int第一个1的位置int pos = __builtin_ffs(0x08); // 4
__builtin_ffsll(x)int第一个1的位置(64位)int pos = __builtin_ffsll(0x08LL);
__builtin_bswap16(x)uint16_t字节交换(16位)uint16_t sw = __builtin_bswap16(0x1234);
__builtin_bswap32(x)uint32_t字节交换(32位)uint32_t sw = __builtin_bswap32(0x12345678);
__builtin_bswap64(x)uint64_t字节交换(64位)uint64_t sw = __builtin_bswap64(0x123456789ABCDEF0);

三、内置函数 - 原子操作

跳转到“三、内置函数 - 原子操作”
函数功能返回值示例
__builtin_sync_fetch_and_add(ptr, val)原子加法旧值int old = __builtin_sync_fetch_and_add(&cnt, 1);
__builtin_sync_fetch_and_sub(ptr, val)原子减法旧值int old = __builtin_sync_fetch_and_sub(&cnt, 1);
__builtin_sync_fetch_and_or(ptr, val)原子OR旧值int old = __builtin_sync_fetch_and_or(&flags, 0x01);
__builtin_sync_fetch_and_and(ptr, val)原子AND旧值int old = __builtin_sync_fetch_and_and(&flags, ~0x01);
__builtin_sync_fetch_and_xor(ptr, val)原子XOR旧值int old = __builtin_sync_fetch_and_xor(&flags, 0x01);
__builtin_sync_add_and_fetch(ptr, val)原子加法新值int new = __builtin_sync_add_and_fetch(&cnt, 1);
__builtin_sync_bool_compare_and_swap(ptr, old, new)CAS操作boolif(__builtin_sync_bool_compare_and_swap(&var, 0, 1))
__builtin_sync_val_compare_and_swap(ptr, old, new)CAS操作旧值int old = __builtin_sync_val_compare_and_swap(&var, 0, 1);
__builtin_sync_synchronize()内存屏障void__builtin_sync_synchronize();
__builtin_sync_lock_test_and_set(ptr, val)原子设置旧值int old = __builtin_sync_lock_test_and_set(&lock, 1);
__builtin_sync_lock_release(ptr)释放锁void__builtin_sync_lock_release(&lock);

四、内置函数 - 其他常用

跳转到“四、内置函数 - 其他常用”
函数功能返回值示例
__builtin_expect(exp, c)分支预测exp的值if(__builtin_expect(err, 0))
__builtin_constant_p(exp)判断编译时常量intif(__builtin_constant_p(x))
__builtin_object_size(ptr, type)对象大小size_tsize_t sz = __builtin_object_size(p, 0);
__builtin_return_address(level)返回地址void*void *ret = __builtin_return_address(0);
__builtin_frame_address(level)栈帧地址void*void *frame = __builtin_frame_address(0);
__builtin_alloca(size)栈上分配void*char *buf = __builtin_alloca(256);
__builtin_types_compatible_p(t1,t2)类型兼容性intif(__builtin_types_compatible_p(typeof(a), int))
__builtin_choose_expr(const, e1, e2)编译时选择-__builtin_choose_expr(1, x, y)
__builtin_offsetof(type, member)成员偏移size_tsize_t off = __builtin_offsetof(struct s, field);
__builtin_prefetch(addr, rw, locality)预取数据void__builtin_prefetch(&data[i+1], 0, 1);

五、内置函数 - 溢出检查

跳转到“五、内置函数 - 溢出检查”
函数功能返回值示例
__builtin_add_overflow(a,b,res)加法溢出检查boolif(__builtin_add_overflow(a, b, &result))
__builtin_sub_overflow(a,b,res)减法溢出检查boolif(__builtin_sub_overflow(a, b, &result))
__builtin_mul_overflow(a,b,res)乘法溢出检查boolif(__builtin_mul_overflow(a, b, &result))
__builtin_uadd_overflow(a,b,res)无符号加法溢出boolif(__builtin_uadd_overflow(a, b, &result))
__builtin_usub_overflow(a,b,res)无符号减法溢出boolif(__builtin_usub_overflow(a, b, &result))
__builtin_umul_overflow(a,b,res)无符号乘法溢出boolif(__builtin_umul_overflow(a, b, &result))
__builtin_sadd_overflow(a,b,res)有符号加法溢出boolif(__builtin_sadd_overflow(a, b, &result))
__builtin_ssub_overflow(a,b,res)有符号减法溢出boolif(__builtin_ssub_overflow(a, b, &result))
__builtin_smul_overflow(a,b,res)有符号乘法溢出boolif(__builtin_smul_overflow(a, b, &result))
扩展语法用途示例
typeoftypeof(expr)获取表达式类型typeof(x) y = x;
语句表达式({ statements; })复合语句作为表达式int max = ({int a=1; int b=2; a>b?a:b;});
零长度数组type array[0]结构体末尾可变数组struct { int len; char data[0]; };
case范围case low ... high:switch范围匹配case 'A' ... 'Z':
指定初始化[index] = value数组指定位置初始化int a[10] = {[5]=1, [8]=2};
复合字面量(type){init}创建匿名对象func((struct point){.x=1, .y=2});
标签值&&label获取标签地址void *ptr = &&label;
__restricttype * __restrict ptr指针无别名void copy(int * __restrict dst, int * __restrict src);
__thread__thread type var线程局部存储__thread int tls_var;
__int128__int128128位整数__int128 big_num;
宏值/含义用途示例
__GNUC__主版本号GCC版本检查#if __GNUC__ >= 7
__GNUC_MINOR__次版本号GCC版本检查#if __GNUC_MINOR__ >= 3
__GNUC_PATCHLEVEL__补丁级别GCC版本检查__GNUC_PATCHLEVEL__
__VERSION__版本字符串编译器版本printf("%s", __VERSION__);
__OPTIMIZE__定义时表示开启优化优化检查#ifdef __OPTIMIZE__
__OPTIMIZE_SIZE__定义时表示-Os大小优化检查#ifdef __OPTIMIZE_SIZE__
__NO_INLINE__定义时禁用内联内联检查#ifndef __NO_INLINE__
__BYTE_ORDER__字节序大小端检查#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
__SIZEOF_POINTER__指针大小架构检查#if __SIZEOF_POINTER__ == 8
__ARM_ARCHARM架构版本ARM检查#if __ARM_ARCH >= 7
__thumb__Thumb模式指令集检查#ifdef __thumb__
__FILE__当前文件名调试信息printf("File: %s", __FILE__);
__LINE__当前行号调试信息printf("Line: %d", __LINE__);
__func__当前函数名调试信息printf("Func: %s", __func__);
__FUNCTION__当前函数名(GCC)调试信息printf("Func: %s", __FUNCTION__);
__PRETTY_FUNCTION__完整函数签名调试信息printf("%s", __PRETTY_FUNCTION__);
__DATE__编译日期版本信息printf("Built: %s", __DATE__);
__TIME__编译时间版本信息printf("At: %s", __TIME__);
__TIMESTAMP__时间戳版本信息printf("%s", __TIMESTAMP__);
指令语法功能示例
diagnostic#pragma GCC diagnostic [action] "[option]"诊断控制#pragma GCC diagnostic ignored "-Wunused"
optimize#pragma GCC optimize ("[option]")优化控制#pragma GCC optimize ("O3")
target#pragma GCC target ("[option]")目标选项#pragma GCC target ("thumb")
push_options#pragma GCC push_options保存选项#pragma GCC push_options
pop_options#pragma GCC pop_options恢复选项#pragma GCC pop_options
reset_options#pragma GCC reset_options重置选项#pragma GCC reset_options
message#pragma message "text"编译时消息#pragma message "TODO: fix this"
warning#pragma GCC warning "text"编译警告#pragma GCC warning "deprecated"
error#pragma GCC error "text"编译错误#pragma GCC error "not supported"
poison#pragma GCC poison identifier禁用标识符#pragma GCC poison malloc
pack#pragma pack(n)结构体对齐#pragma pack(1)
组成部分格式说明示例
基本格式__asm__(code)简单汇编__asm__("nop");
扩展格式__asm__(code : output : input : clobber)完整汇编见下方
输出操作数"=constraint"(var)=表示只写"=r"(result)
输入操作数"constraint"(var)输入变量"r"(value)
输入输出"+constraint"(var)+表示读写"+r"(counter)
破坏列表"register"被修改的寄存器"r0", "r1", "memory", "cc"
volatile__asm__ volatile防止优化__asm__ volatile("dmb");

约束字符表:

约束含义示例
r通用寄存器"r"(value)
m内存操作数"m"(variable)
i立即数"i"(100)
n已知立即数"n"(sizeof(int))
g任意操作数"g"(data)
0-9匹配第n个操作数"0"(same_as_first)
功能实现说明示例
NOP__asm__("nop")空操作__NOP();
WFI__asm__("wfi")等待中断__WFI();
WFE__asm__("wfe")等待事件__WFE();
SEV__asm__("sev")发送事件__SEV();
BKPT__asm__("bkpt #0")断点__BKPT(0);
DMB__asm__("dmb")数据内存屏障__DMB();
DSB__asm__("dsb")数据同步屏障__DSB();
ISB__asm__("isb")指令同步屏障__ISB();
CPSID__asm__("cpsid i")禁用中断__disable_irq();
CPSIE__asm__("cpsie i")启用中断__enable_irq();
MRS__asm__("mrs %0, reg" : "=r"(val))读特殊寄存器MRS r0, PRIMASK
MSR__asm__("msr reg, %0" :: "r"(val))写特殊寄存器MSR PRIMASK, r0
REV__asm__("rev %0, %1")字节反转__REV(value);
CLZ__asm__("clz %0, %1")前导零计数__CLZ(value);

这些表格涵盖了GCC编译器的主要扩展机制,可以作为快速参考手册使用。


来源:CSDN 原文,首次发布于 2025-08-24。