Jul 31, 2013 at 1:58am UTC
where do we properly declare global variables?
I always get this LNK1169 & LNK2005 when I declare a variable to be global. I have 4 cpp and 4 h files.
Jul 31, 2013 at 2:31am UTC
Lets take an example. We want an "int i" in all 4 cpp files
One header needs to have this snipit of code
extern int i;
Include that header in ALL 4 cpp files
ONE cpp file can have this snipit
int i = 1
You can now call i in all 4 cpp files
//Remember that you can only initialize a variable once, so "int i = 1" can only appear once, Any time after that, you need to alter it like "i = 10"
Hope i was clear enough
Jul 31, 2013 at 2:44am UTC
Srictly speaking, the rule is that you are allowed to
define a variable (or function) just the once: the "One definition rule".
http://en.wikipedia.org/wiki/One_Definition_Rule
You will still get a problem if you have int i; (rather than extern int i;) in a header, irrespective of whether you inititialize the variable at the point you define it.
Andy
LNK1169 one or more multiply defined symbols found
LNK2005 symbol already defined in object
Last edited on Jul 31, 2013 at 2:49am UTC
Jul 31, 2013 at 5:47am UTC
Thank you for iterating on what i stated, thats the point i was trying to get at.
You can DECLARE a variable numerous times, in all the files you want to include (extern int i;)
but you can only DEFINE a variable once. (int i;)
Not too good on the grammer, better on the practice
Last edited on Jul 31, 2013 at 5:48am UTC
Aug 1, 2013 at 7:47am UTC
I guess it was never defined, only declared....