954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Share global variables between classes

I had a global variable that could be seen by all of my functions. I was getting too many functions in the same file, so I made functions.h and functions.cpp. I put the function definitions in functions.cpp and the declarations in functions.h. In main.cpp, I include functions.h. The problem is, now I can't see the global variables in the functions that I have moved! Is there a way to see them still?

I thought I might just have to move the global variable definition to BEFORE the include statements, but that didn't change anything, I still get "undeclared identifier".

Thanks,

Dave

daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
 

You might be able to get by with using a macro.

//function.h
#define GLOBAL 9000

In this case, any file that includes funtion.h will have access to a macro called GLOBAL, the result will replace every instance of GLOBAL with the value 9000 during preprocessing. If you go this route, be careful because macros don't follow C++ rules exactly.

BlackJavaBean
Light Poster
39 posts since Feb 2008
Reputation Points: 13
Solved Threads: 7
 

sure I could use a define, but I need to determine the value of this variable at the beginning of the program, so I can't #define it! So can you just not see this type of global variable inside another .cpp file?

daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
 

I getcha, you need to define a global variable that is determined at runtime... Yeah, #define won't do that, unless you want a really ugly macro. Another option is to create a function that creates/passes the global value between files - if you have a lot of globals, it may be a resource hog.
But (this may be Java speaking) if I remember correctly, globals are scoped only to the single source file. So once you leave their file, they go out of scope.

BlackJavaBean
Light Poster
39 posts since Feb 2008
Reputation Points: 13
Solved Threads: 7
 
ivailosp
Junior Poster
129 posts since Apr 2008
Reputation Points: 21
Solved Threads: 22
 

great link! I haven't tried it yet, but it seems like I have to "re" define the variable using the "extern" command:

void FuncThatCantSeeTheVariable()
{
extern int TheVariable;
cout << TheVariable;
}


I'll report back with results.

Thanks!

Dave

daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You