You seem to have undefined behavior -- but one that is probably innocuous on many machines much of the time.
Since your extern
declaration says var
is a double
, when it's actually an int
, attempting to access it as a double causes undefined behavior.
In reality, however, in a typical case, a double
will be eight bytes, where an int
is four bytes. This means when you pass var
to printf, 8 bytes of data will be pushed onto the stack (but starting from the four bytes that var
actually occupies).
printf
will then attempt to convert the first four bytes of that (which does correspond to the bytes of var
) as an int
, which does match the actual type of var
. This is why the behavior will frequently be innocuous.
At the same time, if your compiler was doing bounds checking, your attempt at loading 8 bytes of a four-byte variable could easily lead to some sort of "out of bounds" exception, so your program wouldn't work right. It's just your misfortune that most C compilers don't do any bounds-checking.
It's also possible that (probably on a big-endian machine) instead of the bytes corresponding to var
happening to be in the right place on the stack for printf
to access them as an int
, that the other four bytes that would make up a double
will end up in that place, and it would print garbage.
Yet another possibility would be that the bit pattern of the 8 bytes would happen to correspond to some floating point value that would cause an exception as soon as you tried to access it as a floating point number. Given the (small) percentage of bit patterns that correspond to things like signaling NaN's, chances of that arising are fairly small though (and even the right bit pattern might not trigger anything, if the compiler just pushed 8 bytes on the stack and left it at that).
func()
you changed thevar
. isn't it?extern void func(void);
should be in file1.h and file2.c should include file1.h