arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16 -O3 -c source.c -o output.o
常用选项说明:
- -mcpu=
:指定ARM处理器型号(如cortex-m3, cortex-a7等)
- -mthumb
:生成Thumb指令集代码
- -mfloat-abi=
:浮点ABI(hard/soft/softfp)
- -mfpu=
:指定浮点单元
- -O
:优化级别(-O0到-O3,-Os为空间优化)
__asm__ volatile (
"mov r0, %0\n\t"
"add r0, r0, #1\n\t"
"mov %0, r0"
: "=r" (result) // 输出操作数
: "r" (input) // 输入操作数
: "r0" // 破坏的寄存器
);
内联汇编要点:
- 使用__asm__ volatile
确保不被优化掉
- 正确指定输入/输出操作数
- 声明被修改的寄存器
.syntax unified
.thumb
.text
.global my_function
my_function:
push {r4-r7, lr}
// 函数体
pop {r4-r7, pc}
汇编文件注意事项:
- 使用.syntax unified
支持统一汇编语法
- 明确指定.thumb
或.arm
- 正确保存/恢复寄存器
- 使用.type
和.size
指令增强调试信息
MEMORY {
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 256K
RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 64K
}
SECTIONS {
.text : {
*(.text*)
*(.rodata*)
} > FLASH
.data : {
*(.data*)
} > RAM AT > FLASH
.bss : {
*(.bss*)
} > RAM
}
链接优化技巧:
- 合理分配内存区域
- 使用AT>
实现数据初始化
- 考虑缓存对齐(. = ALIGN(32);
)
循环展开:
#pragma GCC unroll 4
for(int i=0; i<100; i++) {
// 循环体
}
函数内联:
__attribute__((always_inline))
static inline void critical_function() {
// 函数体
}
数据对齐:
__attribute__((aligned(32))) uint32_t buffer[128];
使用内置函数:
uint32_t val = __builtin_arm_ldrex(&shared_var);
反汇编检查:
arm-none-eabi-objdump -d output.elf > disassembly.txt
性能分析:
perf stat -e cycles,instructions,cache-misses ./program
GCC优化报告:
gcc -O3 -fopt-info-optimized -c source.c
寄存器分配问题:
-ffixed-rX
保留特定寄存器性能瓶颈:
-fprofile-generate
和-fprofile-use
进行基于性能分析的优化代码大小优化:
-Os
优化级别-ffunction-sections -fdata-sections
配合--gc-sections
通过合理组合这些技巧,可以显著提升ARM嵌入式系统的性能,同时保持代码的可维护性和可移植性。