Why do I have to pass libraries in the end of linker line? [duplicate]

半腔热情 提交于 2021-01-29 17:30:43

问题


Command like this will work:

(LD) $(LDFLAGS) -o reip.app newlib/crt0.o reip.o renetif.o fs.o httpd.o liblwip.a newlib/libc.a

But if I place *.a before *.o files - it will be not able to find functions from libs.

I've searched through some old projects and found in makefiles lines like these:

$(CC)  $(LIBS) -o $(TARGET) JukeboxMain.o JukeboxPlayer.o ...

which doesn't work either until I move $(LIBS) to the end of line. But I remember it was working for me long time ago. Could someone please answer what changed and why it doesn't work anymore ) P.S. I'm not a big fan of playing with compilers, linkers and other tools - I mostly prefer to create something ;)


回答1:


I can't answer you as to why you think it might have worked before. But I can tell you why it doesn't work in general. Most POSIX-style linkers, which includes the GNU binutils ld using on GNU/Linux and others, are single-pass linkers.

That means they walk the elements listed in the command line from the start to the end one time and they don't go back. When the linker starts it's basically looking for one symbol, main. As it walks the command line, any object file (foo.o) the linker finds is always added to the executable. The object provides a list of symbols which are defined, and a list which are undefined (needed from other objects).

When the linker hits a static library (libfoo.a), it looks through the object files in that library and if an object contains any symbol which the linker needs, it adds that object to the executable. If it does not contain any symbol the linker needs, it skips that object.

At the end of the command line, if any symbol was needed but not found, then the link fails.

So, you can see that in order to be sure everything is found in a single pass, the things that NEED symbols from libraries must come before the libraries that provide those symbols, or else when the linker hits the library in its single pass it won't know that the libraries are needed and will skip them.



来源:https://stackoverflow.com/questions/21854309/why-do-i-have-to-pass-libraries-in-the-end-of-linker-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!