一、内存与结构控制类
1. packed (内存对齐控制)
struct __attribute__((packed)) SensorData
{
uint8_t id; // 1字节
uint32_t value; // 4字节(取消对齐填充)
}; // 总大小=5字节(默认可能有填充到8字节)
- 作用:取消结构体/联合体的内存对齐
- 适用编译器:GCC/Clang/IAR/Keil
- 等价写法:
- Keil:
__packed struct - IAR:
#pragma pack(1)
- Keil:
2. aligned (强制对齐)
uint32_t buffer[4] __attribute__((aligned(16))); // 16字节对齐
- 作用:指定变量或结构体的对齐方式
- 典型应用:DMA缓冲区、SIMD指令数据
3. section (指定存储段)
__attribute__((section(".bootloader"))) void Boot_Entry() {}
- 作用:将函数/变量放入指定内存段
- 应用场景:Bootloader代码隔离、特殊内存区域分配
二、函数行为控制类
1. naked (裸函数)
__attribute__((naked)) void ISR_Handler() { __asm("MOV R0, #0x01\nBX LR"); }
- 作用:禁止编译器生成函数序言/尾声
- 应用场景:中断服务程序、上下文切换
2. weak (弱符号)
__attribute__((weak)) void Default_Handler() {}
- 作用:允许符号被重定义
- 典型应用:库函数默认实现(可被用户覆盖)
3. noinline (禁止内联)
__attribute__((noinline)) void Critical_Func() {}
- 作用:强制函数不被编译器内联优化
- 应用场景:调试关键函数、性能测试
三、中断相关类
1. interrupt (中断函数)
// GCC void __attribute__((interrupt)) TIM1_IRQHandler() {}
// IAR __interrupt void TIM1_IRQHandler() {}
- 作用:声明中断服务函数
- 编译器差异:
- Keil:
__irq - IAR:
__interrupt
- Keil:
2. naked + interrupt 组合
__attribute__((naked, interrupt)) void HardFault_Handler()
{
__asm("TST LR, #4\nITE EQ\nMRSEQ R0, MSP\nMRSNE R0, PSP\nB HardFault_DebugHandler");
}
- 典型应用:硬件异常处理(需手动保存上下文)
四、优化控制类
1. optimize (优化级别)
__attribute__((optimize("O0"))) void NoOptimize_Func() {}
- 作用:指定单个函数的优化级别
- 应用场景:调试关键代码时禁用优化
2. used (强制保留符号)
__attribute__((used)) static void UnusedButImportant() {}
- 作用:防止未使用的函数被优化删除
3. unused (忽略未使用警告)
void Logging(__attribute__((unused)) int level) {}
- 作用:抑制编译器关于未使用参数的警告
五、硬件相关类
1. volatile (易变性)
volatile uint32_t *reg = (uint32_t*)0x40021000;
- 标准C关键字,但常用于嵌入式:
- 告诉编译器不要优化对内存/寄存器的访问
2. at (绝对地址定位)
// Keil语法 uint32_t __at(0x20001000) SharedBuffer;
- 作用:将变量定位到指定物理地址
- 等价实现:
- GCC:
__attribute__((section(".ARM.__at_0x20001000")))
- GCC:
六、跨编译器对照表
| 功能 | GCC/Clang | Keil (ARMCC) | IAR |
|---|---|---|---|
| 取消结构体对齐 | __attribute__((packed)) | __packed | #pragma pack(1) |
| 中断服务函数 | __attribute__((interrupt)) | __irq | __interrupt |
| 绝对地址定位 | __attribute__((section)) | __at | __no_init + 链接脚本 |
| 弱符号 | __attribute__((weak)) | __weak | __weak |
七、使用建议
-
可移植性警告
这些关键字都是编译器扩展,建议通过宏定义隔离:#ifdef __GNUC__ #define PACKED __attribute__((packed)) #elif defined(__ICCARM__) #define PACKED __packed #endif -
关键场景示例
Flash操作函数(需绝对地址访问):__attribute__((section(".flash_ops"))) __attribute__((aligned(4))) void Flash_Program(uint32_t addr, const uint8_t *data) { // 直接操作Flash控制器的汇编指令 }
1841

被折叠的 条评论
为什么被折叠?



