For example, let's say I build a library a.lib that has two files: foo.c and bar.c. foo.c calls a function void bar()
defined in bar.c.
Now let's say I have an executable that I'm going to create that has two files: main.c and bar.c. This bar.c also has void bar()
defined, but with a different implementation.
When I link the executable with a.lib, which void bar()
will be called by the executable?
Let us assume that:
libfoobar.a
(or libfoobar.lib
) and is in directory ./lib
. foo.c
defines foo()
and foo()
calls bar()
. bar.c
defines bar()
. bar.c
also defines bar()
— a different implementation. main.c
calls both foo()
and bar()
. Your linking command line looks like:
cc -o program main.o bar.o -L ./lib -lfoobar
Then:
bar()
from the program file bar.c
(because that was explicitly included on the command line, ahead of the library). foo()
from the library file foo.c
, but the bar()
that it calls will be the one from the program file bar.c
, not the one from the library. If there are more symbols involved, so that the library foo.c
calls functions which are only available in the library bar.c
(the program bar.c
does not implement all those functions), then the linking will fail because the program contains the program's bar.c
(unconditionally), but it also needs the library's bar.c
, but that gives you a double definition of the function bar()
— which is an error.
The twists and turns can get serious. Simple rule of thumb — don't do it. That is, don't make the program's bar.c
provide the symbol that is also available in the library's bar.c
. If you must and there are other entry points involved, then you have to work a lot harder.
Don't put libraries before object files; then you'll fail with bar()
doubly defined. Libraries go after object files in the link list. You do need to get multiple (static) libraries in the correct order, though. Or use special options to make the loader rescan libraries, etc.
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.