简体   繁体   中英

g++ has unreferenced function error with lib

The project has three files, main.c, file1.c and file2.c

gcc -o main.o -c main.c
gcc -o file1.o -c file1.c
gcc -o file2.o -c file2.c

Method 1, works well

g++ -o main.exe main.o file1.o file2.o

Method 2, failed

ar rv lib.a file1.o file2.o
g++ -o main.exe lib.a main.o
main.c:(.text+0xa): undefined reference to `ini_load'

Anything wrong in the commands? Thx

The position in the command line matters.

When you list a library on the command line, it's used to satisfy unresolved references in existence at that time. From the gcc man-page:

It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, foo.o -lz bar.o searches library z after file foo.o but before bar.o . If bar.o refers to functions in z , those functions may not be loaded.

If you change it to:

g++ -o main.exe main.o lib.a

then it should work fine, as all the unresolved references in mian.o will be searched for in the objects within lib.a .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM