Lothar
Lothar

Reputation: 13067

Linking two object files with a common symbol

If i have two object files both defining a symbol (function) "foobar".

Is it possible to tell the linker to obey the obj file order i give in the command line call and always take the symbol from first file and never the later one?

AFAIK the "weak" pragma works only on shared libraries but not on object files.

Please answer for all the C/C++ compiler/linker/operating system combinations you know cause i'm flexibel and use a lot of compiles (sun studio, intel, msvc, gcc, acc).

Upvotes: 1

Views: 2721

Answers (3)

Christy Wald
Christy Wald

Reputation: 329

You can make it as a .a file... Then the compiler gets the symbol and doesn't crib later

Upvotes: 0

t0mm13b
t0mm13b

Reputation: 34592

There is a danger here, the keyword here is called Interpositioning dependant code.

Let me give you an example here:

Supposing you have written a custom routine called malloc. And you link in the standard libraries, what will happen is this, functions that require the usage of malloc (the standard function) will use your custom version and the end result is the code may become unstable as the unintended side effect and something will appear 'broken'.

This is just something to bear in mind.

As in your case, you could 'overwrite' (I use quotes to emphasize) the other function but then how would you know which foobar is being used? This could lead to debugging grief when trying to figure out which foobar is called.

Hope this helps, Best regards, Tom.

Upvotes: 2

Clifford
Clifford

Reputation: 93476

I believe that you will need to create a static library from the second object file, and then link the first object file and then the library. If a symbol is resolved by an object file, the linker will not search the libraries for it.

Alternatively place both object files in separate static libraries, and then the link order will be determined by their occurrence in the command line.

Creating a static library from an object file will vary depending on the tool chain. In GCC use the ar utility, and for MSVC lib.exe (or use the static library project wizard).

Upvotes: 2

Related Questions