quote:Original post by petewoodNone of that works (and I want x to be 2 in header.h)
which begs the questions: why do you want x to be 2 in header.h? what does it mean? why do you want a new variable x made in every file that header.h is included?
the explanation of oluseyi''s answer is this:
you want one copy of the variable x to be available to your program. by declaring x in a header you can include that header in places that need to know about x. the statement x = 2 is not a declaration though. it is a definition. whats that? there''s a difference?
the difference:
the declaration will tell your program that somewhere there exists a variable x. it will be able to find it when the program finally links.
the definition will actually declare and define the variable. that variable is the object. you can only have one of them. that''s why it''s a problem to put the definition in the header file.
the solution:
put a definition of the variable in one cpp file.
put a declaration of the variable as ''extern''. this means it will look for it elsewhere at link time (and hopefully find it defined in your cpp file)
Hehe. You took in consistently =)
I wan''t only one x, every file that includes header.h must refer to that header''s x when using and changing it.
This works good if I declare x as a static but when I use extern it doesn''t work. I''ve tried most combinations of it but without luck.
Is anyone perfectly sure of how this should be done?
It''s not a hard question, really. =)