I am unable to understand the weird behaviour of the program. It throws a warning but the output is surprising. I have 3 files, file1.c, file2c, file1.h
file1.c :
#include "file1.h"
extern void func(void);
int main(void)
{
func();
printf("%d\n",var);
return 0;
}
file2.c:
int var;
void func(void)
{
var = 1;
}
and file1.h is :
#include<stdio.h>
extern double var;
When I compile and run, it shows a warning as expected but on printing prints 1. But how is it possible when I am changing the var declared in file2.c
Just setting the type on an
externdefinition doesn’t change the value stored in memory – it only changes how the value is interpreted. So a value of0x0001is what is stored in memory no matter how try to interpret it.Once you’ve called func() you’ve stored the value
0x0001in the location whereais stored. Then inmainwhenais passed toprintfthe value stored at locationaplus the next 4 bytes (assuming 32bits) is pushed onto the stack. That is the value0x0001xxxxis pushed onto the stack. But the%dtreats the value passed in as an int and will read the first 4 bytes on the stack, which is0x0001so it will print 1.Try changing your code as follows:
file1.c :
file2.c:
and file1.h is :
You will probably get the output
1 2(although this depends on how the compiler stores the variables, but it’s likely it will store them in adjacent locations)