Ashley Duncan Ashley Duncan - 2 months ago 26
C Question

How does gcc decide which libraries to implicitly include?

With reference to this question:

On an embedded project for a small micro I found my compiled code size was much larger than expected. It turned out it was because I had included code that used assert(). The use of assert was appropriate in the included code but caused my compiled code size to almost double.

The question is not around if/when assert should be used but how the compiler/linker decides to include all the necessary overhead for assert.

My original question from the other post:

It would be helpful if someone could explain to me how gcc decides to include library functions when assert is called? I see that assert.h declares an external function __assert_func. How does the linker know to reference it from a library rather than just say "undefined reference to __asert_func"?

nos nos
Answer Source

When configuring a toolchain, the authors decide which libraries that should be linked to by default.

Often this is includes runtime startup/initializing code and a library named libc which includes an implementation of the C standard, and any other code the authors deem relevant (e.g. libc might also implement Posix, any custom board specific functions etc.) and for embedded targets it's not unusual to also link to a library implementing an RTOS for the target.

You can use the -nodefaultlibs flag to gcc to omit these default libraries at the linking stage.

In the case of assert(), it is a standard C macro/function , which is normally implemented in libc. assert() might print to stdout if it fails, so using assert() could pull in the entire stdio facility that implements FILE* handling/buffering, printf etc., all which is implemented in libc.

You can see the libraries that gcc links to by default if you run gcc -v for the linking stage.