Question

I've created my lib.a file with several

gcc -c file.c -o file.o

then

ar sr lib/libtest.a file1.o file2.o file3.o

confirmed with

ar -t lib/libtest.a
file1.o
file2.o
file3.o

but when I try to compile test aplication

gcc lib/libtest.a test.c -o test

I got undefined reference in function main: to used function from file1.o, file2.o, file3.o

Was it helpful?

Solution

Order matters with libraries - try:

gcc test.c -o test lib/libtest.a 

Basically, the linker reads the library when it comes across it on the list of input files (this may not be exactly how things work, but I think it works well as a rule of thumb) and will resolve any still-undefined references remaining. When it moves on to the next input, it won't look to that library again for any new unresolved references it picks up along the way.

(Note: there are certain linker options that can change this behavior, but they seem to be rarely used and probably have their own set of drawbacks so I don't discuss them here. this kind of problem is usually resolved by reordering the linker's input file list).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top