extern int i. so is it a definition or a declaration?
I'm completely confused. the famous stupid example x/y: we have 2 cpp files the first file extern int x; int y = x+1;
Second file extern int y; int x = y+1;
It is clear that depending on which file is executed first, there will be a different result. In eckell, it is stated that for all static objects (probably meaning those allocated in a static memory area), the layout and loading mechanism guarantees that before performing a dynamic operation, initialization defined by the programmer, static data will be initialized with zeros. in this regard, there is a misunderstanding . Do I understand correctly that, for example, if file #1 is triggered first x is roughly speaking no declaration, but already a full-fledged definition, since it acquires both the address and the value zero ???
1 answers
For the source file, this is a declaration. It will record that there is a variable x with some address, which will be known later. It will become known later-when linking...
Here's what it looks like in VC++:
extern int y;
int x = y + 1;
Here is the assembler: somewhere outside is declared y
EXTRN ?y@@3HA:DWORD ; y
Inside, x
is declared and defined - it has its own place in memory and a specific address:
_BSS SEGMENT
?x@@3HA DD 01H DUP (?) ; x
_BSS ENDS
And the initialization code is added:
??__Ex@@YAXXZ PROC ; `dynamic initializer for 'x'', COMDAT
; File G:\Tmp\Test\x.cpp
; Line 2
mov eax, DWORD PTR ?y@@3HA ; y
inc eax
mov DWORD PTR ?x@@3HA, eax ; x
ret 0
??__Ex@@YAXXZ ENDP ; `dynamic initializer for 'x''
Which refers to an external a variable.
It works the same way in the second file - with the external x
.
Well, the decoupling of addresses occurs already at the stage of linking (linking), and not compilation. Not to mention getting values by variables, which is obtained here only when executed...