Forums

Embedded C - Linking obj file

Started by splee2 2 weeks ago3 replieslatest reply 2 weeks ago54 views

Ok this question seems basic:

A C project consists of myMain.c, and myFunc.c

myFunc.c - contains several functions, e.g myfunc1(), myfunc2(), myfunc3(), etc.

myMain.c - only calls myfunc1(). All other functions are never used

Why does the Linker links the whole of myFunc.obj to myMain.obj? Why doesn't it just link the function myfunc1() to the main obj file? If so then the code size will be significantly reduced, ie. unused functions will not be linked

[ - ]
Reply by QLNovember 12, 2020

The information you provide is incomplete. For example, which toolchain are you using?

If this is GCC, are you using the `-ffunction-sections` or `-fdata-sections` options?

Other toolchains, can also perform link-time optimization. Some toolchains, like for instance IAR or ARM/Keil allow you to apply "multi-file compilation", where the whole application is compiled and optimized at once, regardless of how you have partitioned the code into files. 

[ - ]
Reply by jmford94November 12, 2020

Many if not all linkers will link in all the objects that are in a single file.  You can split up the .obj into separate files and put them in a library to be more selective about what gets linked in.  

I'm not familiar with optimizers like QL mentions, so maybe your toolchain will do that optimizing for you.


[ - ]
Reply by KocsonyaNovember 12, 2020

Usuallylinkers use object files in their entirety. 

If you want selective linking, split myFunc.c into the separate functions, myFunc1.c, myFunc2.c and so on, compile them individually and build a library from them.

From libraries, the linker will only get what is needed for the build.