tags:

views:

129

answers:

2

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).

+2  A: 

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).

Clifford
@Clifford: Will there be any error reported, the same symbol is defined in `1.o` and `2.o` (both are in `libsome.a`), and I am trying to link statically against this library?
dma_k
@dmak_k: I have no idea; why would you do such a thing!? Two things could happen; 1) The linker could find both definitions and report an error; 2) It could resolve the symbol with the first one found, in which case it would depend on the order the object files appeared in the library. In most cases you'd want (1) to happen, since (2) is ambiguous and would lead to hard to find bugs. You could of course just try it.
Clifford
+1  A: 

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.

tommieb75