I am using Eclipse to develop bare-metal applications. I link against newlib, so I provided my own implementation of _sbrk(). This function was normally included in my project, and everything was working great.
Now I try to move this function to a static library that I have developed over the last months.
During linking I get an undefined reference to _sbrk
error. The path the file is located is properly included to the Eclipse settings (other files in the same directory are linked correctly).
Obviously there is some problem with the order the linker goes through my code, and this function is discarded.
I tried using __attribute__((used))
, without luck.
How can I overcome this problem, through the Eclipse settings? (Makefile based or command line compilation is not the solution I need).
To get this to work you need to ensure that your "new" static library appears after newlib (C library) in the command line to the linker. GCC will automatically add -lc
to the command line of the linker after all the other objects and libraries. You are however allowed to have them repeated if need be.
So assume your library is called mylibrary
and your application and main file are called SO, setting linker options up like this will work:
gcc -o SO ./src/SO.o -lc -lmylibrary
This resolves to this (simplified!) on the linker:
ld -o SO ./src/SO.o -lc -lmylibrary -lc -lgcc
In the settings this looks like:
To get the right combination you may have to adjust/add repeated somewhat. Especially if "mylibrary" then depends on other parts of newlib that in turn depend on other parts of mylibrary.
Another alternative is to ensure that _sbrk
simply is linked in early. This can be done in a number of ways:
_sbrk
from an object file that is passed directly to GCC. e.g.:
_sbrk
from an extern (i.e. not optimized out) function that is itself not used_sbrk
in a c file_sbrk
reference to an assembly file, perhaps in a section that does not end up on the target if space is tightYou weren't asking the why this happens, but for any other readers who want to know there is a good Q&A over here: Why does the order in which libraries are linked sometimes cause errors in GCC? for more details on why the order matters.