简体   繁体   中英

Newlib stubs in static library

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).

Repeating Libraries

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.

Force Linking Early

Another alternative is to ensure that _sbrk simply is linked in early. This can be done in a number of ways:

  • adding dependency in linker script
  • adding use of _sbrk from an object file that is passed directly to GCC. eg:
    • call _sbrk from an extern (ie not optimized out) function that is itself not used
    • take the address of _sbrk in ac file
    • add _sbrk reference to an assembly file, perhaps in a section that does not end up on the target if space is tight

Why?

You 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.

I solved my issue, by just adding the following code to my linker script.

GROUP(
   libgcc.a
   libg.a
   libc.a
   libm.a
   libnosys.a
 )

This way no changes where needed in any settings, or the linker commands issued.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM