Global variables in include file

R

razael1

Hi,

I am declaring a global variable in a .h file like this:

extern MyClass object;

Then I include the .h file in other files and try to use object. I get
"object not declared", but then when I add:

MyClass object;

to the file I am including the .h file in, I get "multiple definitions
of object". How can I fix this?

Thanks,
Colin
 
J

Joseph Paterson

You shouldn't define global variables in header files, you should only
declare them there.
For example, in myFile.cpp you would have:

int myGlobal = 1;

and in myFile.h you would have:

extern int myGlobal;

now all files that include myFile.h will have access to the global
variable myGlobal.

Joseph.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top