I'm linking against a static library that I don't have the original source code to, and it's absolutely critical that I produce the smallest binary. Although unused .text
sections from this library get stripped, if (e.g.) there's a .o
containing even a single function that my code uses, then the entire .text
section of that object gets linked into the final executable. Is there a way to link more selectively?
I tested with a C source file and its corresponding assembly (generated via gcc -S test.c
):
#include <stdio.h>int foo(int num){ return num * 2;}void main(){ int res = foo(5); printf("%d", res);}
Running gcc --ffunction-sections -c test.c
results in an object file with two different sections for main
and foo
, which is my desired result. This way, I can link with --gc-sections
and only link the functions I actually use.
Running gcc -S test.c; gcc -c --ffunction-sections test.s
however, results in an object file with one single .text
section for both main
and foo
. If I link against this (e.g., with the intent of only using foo
), the final executable will still contain the function main
, even though I & foo
do not use main
. This doesn't really surprise me, but is there a way to functionally achieve having each function in their own section when I only have the disassembly (assembly) available to me?
I investigating objcopy
with various flags, but it seems that tool is rather limited. I'd rather avoid a lethargic manual process if possible.