Undefined reference to my own library

余生长醉 提交于 2020-01-15 08:48:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!