1

I have declared an extern global variable inside my main.h header file like this:

extern int variable;

Then, I defined the same global variable inside my main.c file like this:

int variable = 16;

The thing is that I am using another file called test.c, and I have included main.h header included inside. But I cannot gain access the the "16" value that I defined the extern with inside main.c. When I call "variable" inside test.c, the value of "variable" is "0". Should not any .c file that includes my main.h header have access to the "16" value since I have already defined my "variable" inside main.c???

Thanks

Pototo
  • 691
  • 1
  • 12
  • 27
  • 3
    Yes, `test.c` should see the `16`. So you need to show us a [Minimal Complete Verifiable Example](http://stackoverflow.com/help/mcve) – user3386109 Mar 18 '15 at 22:33
  • By what you have described, the value of `variable` in `test.c`, should be 16. ***[You have described it correctly](http://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files-in-c)***: Create variable with extern scope in header file. Define same variable in a .c, assigning an initialization value. Access variable in any other .c file that #includes the .h in which extern variable is created. – ryyker Mar 18 '15 at 22:34
  • Make sure that "`int variable=16;`" statement is outside of all functions, or it won't be an `extern`. If it's inside a function, that will just be a local variable that no other function can see. – Mike Housky Mar 18 '15 at 22:34
  • It seems to be likely that some other variable with the same name overshadows the global one, in one cpp file or another. Impossible to say without actual source. – Frax Mar 18 '15 at 22:47
  • 1
    [existing answer](http://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files-in-c/1433387#1433387). Your question may have already been answered here. – Mike Jablonski Mar 18 '15 at 23:55

2 Answers2

1

When your Including your main.h header file, the copy of the file will included in the main.c program.

when your alterate into the main.c file , it will not affect the original file.So the value will not affect the original file, and when your are including the file again in the test.c file .

Then the copy of the main.h will added to the test.c file

Bhuvanesh
  • 1,269
  • 1
  • 15
  • 25
1

You are just including the file main.h in the programs. When you include in main.c the variable will be 16 and the value will be updated in the main.h. But when you compile the test.c the value of variable will be 0 initially. So when you print the value it will be 0.

main.c and test.c will be executed in two separate process, so if the value changes in the main.c it will be not updated in the test.c process.

Only within the single process the value will be updated.

sharon
  • 734
  • 6
  • 15