Search code examples
cstatic-librariesunix-ar

Why the order of object files is important for static libraries?


I create some files: file1.c file2.c file3.c I compile them using gcc -c file1.c and i did the same for other files, and i get object files. Later i used ar tool to create static library.

Everythink works correctly, but ar has option

ar -m -a file.o lib.a filetomove.o

to move object files in library, why order of object files is important? Please, show me example where object files must be in correct order.


Solution

  • This is less and less of a problem as time goes on, but for a long time linkers were single pass. That means if a symbol was defined in a.o and referenced in b.o, the linker had to "see" b.o before a.o or it would never find a definition for the reference.

    In other circumstances, sometimes a "default" function is provided in a library that is linked last. This is a popular technique in embedded systems development. You can provide an override function by linking it in a static library or object module, but if you don't, the last library will provide a symbol that satisfies the linker.