我正在尝试使用clang编译器和GNU Arm嵌入式工具链汇编器+链接器+库来为STM32F103构建一个LED闪烁器。我的主机系统是Debian x86_64。我使用在STM32CubeMX(基于GCC)中生成的Makefile项目,并对makefile进行了一些更改。但是,当使用原始Cube项目创建的bin为5KB时,结果二进制文件的大小为16KB。而且,我注意到使用sprintf()(对于UART)将大小增加到51KB。我知道动态内存分配可能会占用很多空间,但是对于相同的代码,在Cube项目中创建的bin的大小仅为7KB。
如何减小clang + GNU工具链配置的二进制大小?
编译:
clang -c --target=armv7m-none-eabi -mcpu=cortex-m3 -mthumb $(INCLUDES) -O2 -fdata-sections -ffunction-sections file.c -o file.o
arm-none-eabi-as startup_stm32f103xb.S -o startup_stm32f103xb.o
链接:
clang -v -nostdlib --target=armv7m-none-eabi -mcpu=cortex-m3 \
--ld-path=/path/to/gcc-arm-none-eabi-9-2020-q2-update/bin/arm-none-eabi-gcc \
-TSTM32F103C8Tx_FLASH.ld \
-L"/path/to/gcc-arm-none-eabi-9-2020-q2-update/lib/gcc/arm-none-eabi/9.3.1/thumb/v7-m/nofp" \
-L"/path/to/gcc-arm-none-eabi-9-2020-q2-update/arm-none-eabi/lib/thumb/v7-m/nofp/" \
$(OBJECTS) startup_stm32f103xb.o \
-o out
获取二进制文件:
arm-none-eabi-objcopy -O binary -S out out.bin
某些功能和对象确实很占用空间,主要是那些与动态内存管理有关的功能,例如:
$readelf -a out
...
775: 080049b9 6992 FUNC GLOBAL DEFAULT 2 _svfprintf_r
964: 20000444 1032 OBJECT GLOBAL DEFAULT 7 __malloc_av_
993: 08006709 3784 FUNC GLOBAL DEFAULT 2 _dtoa_r
994: 080078e5 1372 FUNC GLOBAL DEFAULT 2 _malloc_r
1032: 08008b29 2852 FUNC GLOBAL DEFAULT 2 _svfiprintf_r
1073: 08009e41 3372 FUNC GLOBAL DEFAULT 2 _vfiprintf_r
...