function reorder in binary
main.c
#include <stdio.h>void funcA() {printf("This is funcA\n");
}void funcB() {printf("This is funcB\n");
}int main() {funcB();funcA();return 0;
}
linker.ld
SECTIONS {. = 0x08000000;/* 可执行段:.text */.text : ALIGN(4){*(.text.funcB)*(.text.funcA)*(.text.main)*(.text*)} :text/* 只读数据段:.rodata */.rodata : ALIGN(4) {*(.rodata*)} :rodata/* 可读写段:.data */.data : ALIGN(4) {*(.data*)} :data/* 未初始化的段:.bss */.bss : ALIGN(4) {*(.bss*)} :data/DISCARD/ : { *(.note.GNU-stack) }
}/* 定义段权限 */
PHDRS {text PT_LOAD FLAGS(5); /* R + X */rodata PT_LOAD FLAGS(4); /* R */data PT_LOAD FLAGS(6); /* R + W */
}
build.sh
#!/bin/bash# 编译,开启 -ffunction-sections 让每个函数落在不同 section
gcc -ffunction-sections -c main.c -o main.o# 使用自定义链接脚本链接,控制函数顺序
gcc main.o -Wl,-T,linker.ld -o mybinary# 使用 nm 查看最终函数地址顺序
echo "Function order in binary:"
nm -n mybinary | grep ' T '
objdump -h main.o | grep func4 .text.funcA 0000001a 0000000000000000 0000000000000000 0000005c 2**05 .text.funcB 0000001a 0000000000000000 0000000000000000 00000076 2**0