Network Theory Ltd - publishing free software manuals
An Introduction to GCC - for the GNU compilers gcc and g++
by Brian J. Gough, foreword by Richard M. Stallman
Paperback (6"x9"), 124 pages
ISBN 0954161793
RRP £12.95 ($19.95)

"A wonderfully thorough guide... well-written, seriously usable information" --- Linux User and Developer Magazine (Issue 40, June 2004) Read more >>>

2.4.3 Link order of object files

On Unix-like systems, the traditional behavior of compilers and linkers is to search for external functions from left to right in the object files specified on the command line. This means that the object file which contains the definition of a function should appear after any files which call that function.

In this case, the file 'hello_fn.o' containing the function hello should be specified after 'main.o' itself, since main calls hello:

$ gcc main.o hello_fn.o -o hello   (correct order)

With some compilers or linkers the opposite ordering would result in an error,

$ cc hello_fn.o main.o -o hello    (incorrect order)
main.o: In function `main':
main.o(.text+0xf): undefined reference to `hello'

because there is no object file containing hello after 'main.o'.

Most current compilers and linkers will search all object files, regardless of order, but since not all compilers do this it is best to follow the convention of ordering object files from left to right.

This is worth keeping in mind if you ever encounter unexpected problems with undefined references, and all the necessary object files appear to be present on the command line.