lychee
lychee

Reputation: 1851

Ordering of object files and libraries in static linking

I've created a simple static library libvec.a with AR tool from simple addv.o and multo.o. The object file addv.o contains 1 function symbol (addvec) and multo.o contains 1 function (multvec). I have also written a simple program to test it (driver.c which adds 2 vectors and uses addvec function from the library; also it has included vector.h that defines the function prototypes). And then I compiled it with

gcc -static driver.o ./libvec.a

and everything went okay. But at first I tried to compile it with

gcc -static ./libvec.a driver.o

and I got an error:

undefined reference to 'addvec'

I'm wondering why I got an error when I specified the library first? Should the ordering matter?

Upvotes: 3

Views: 2985

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753705

Always link object files before libraries, period.

The trouble is that the linker scans the library, and it is looking for main(). It doesn't find it, so it doesn't pull anything out of the library. Then it scans driver.o, finds what is looking for, but not the things that were in libvec.a (which it has forgotten about as they weren't relevant). So, the functions from libvec.a are unsatisfied references — and the linking fails.

Note that 'object files before libraries' works when linking with static libraries or shared libraries.

Upvotes: 9

Related Questions