1

Say I have two .cpp files and in one of them I wrote

extern int i ;

and in another one I define the i variable.

Now how the linker knows that in the first file the i should be linked to the address of "i" in the second file? This question arises, because as I know, the object file does not have any info about variable names (it knows only addresses) (see this link).

I am really confused in this.

Community
  • 1
  • 1
Narek
  • 38,779
  • 79
  • 233
  • 389
  • The object certainly does know about names. Well, symbols, and symbols are created deterministically from the names and in simple cases are a 1:1 map. Those symbols however may not make it to the final linked form (that is, the run-time form). though even then, for shared libraries and RTTI a lot of symbol information is still retained. – edA-qa mort-ora-y Mar 17 '11 at 09:59

2 Answers2

3

Some light reading: Beginner's Guide to Linkers.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
2

The object code has symbol definitions in it. The linker uses these to resolve references to symbols. The symbols are not part of the executable code, and cannot be read by code that is contained within the object file (hence the answer to the question to link to).

The linked executable may also have symbols in it (e.g. for use by a debugger), or may have symbols removed at link stage (or later) since they are of no use to the code contained within the executable.

qbert220
  • 11,220
  • 4
  • 31
  • 31