We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
In my project I have two files. as follows File A int x; main() { x=2; } File B extern int x; { x=4; } When I compile both files independatly, there is no error. When I link both modules, there is no error. But when I execute this program, I am unable to assign x = 4. Always the value of x remains 2. But in file A I can assign any value to x. Why I can not assign any value to x in File B? I am trying this with Keil compiler.
Actually there can be no "expected answer" from your displayed code at all, because it doesn't output anything, anywhere. For what it's worth, the linker would be in its full right to just optimize 'x' away, since you never use the value for anything.
"the linker would be in its full right to just optimize 'x' away" To be precise, the Compiler would perform this optimisation...
the Compiler would perform this optimisation Not on a global variable like this it wouldn't. Or if it did, that'd be a bug. The compiler simply doesn't have the information needed to justify eliminating any object of external linkage --- it doesn't know what other translation units might be doing with it.
"Not on a global variable like this it wouldn't." Oh yeah...! Obviously the scope of my reply was too limited (didn't read the whole thread). Sorry.
The end of your program is undefined. You should have a while (1) loop in the 'main' function to avoid that your program jumps to nowhere.