Joachim W
Joachim W

Reputation: 8197

how does ld deal with code that is supplied twice (in a source file and in a library)?

Suppose we call

gcc -Dmyflag -lmylib mycode.c

where mylib contains all of mycode but is compiled without -Dmyflag. So all functions and other entities implemented in mycode are available in two versions to the loader. Empirically, I find that the version from mycode is taken. Can I rely on that? Will mycode always overwrite mylib?

Upvotes: 1

Views: 87

Answers (1)

Employed Russian
Employed Russian

Reputation: 213877

Empirically, I find that the version from mycode is taken.

Read this explanation of how linker works with archive libraries, and possibly this one.

Can I rely on that?

You should rely on understanding how this works.

If you understood material in referenced links, you'll observe that adding main to libmylib.a will invert the answer (and if mycode.c also contains main, you'll get duplicate symbol definition error).

If you are using a dynamic library libmylib.so, the rules are different, and the library will always lose to the main binary, although there are many complications, such as LD_PRELOAD, linking the library with -Bsymbolic, and others.

In short, you should prefer to not do this at all.

Upvotes: 1

Related Questions