问题
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
回答1:
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).
来源:https://stackoverflow.com/questions/10421491/undefined-reference-to-my-own-library