Public Group

quick c++ question about creating varibles and using them in other source files.

This topic is 4807 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

hello all, I yet another question for all of you c++ gurus out there. i have a source and header file (for a class) called screen. now one of the functions in this class needs to access my main_window_handler (of type HWND) now, if i put the declarion at the top of the source file, and than include the header file in main.cpp, main.cpp functions do not know it exists. however if i put it in both main.cpp and screen.cpp, I get an error saying i've declared it twice. keeping main_window_handler as a grobal varible, how do i go about getting this to work? thanks. PS: also, if anyone know of a web page that how this such of thing works, can you post the url?

Share on other sites
Put it in one header that is included by both source files.
It might have to be declared as extern too.

Share on other sites
what does declaring something as extern do?

Share on other sites
CJWR,

To solve your problem, declare the variable in one of the .cpp files and then declare it as extern in the second .cpp file. (extern is short for 'external')

To declare it as extern use the exact same syntax you used to declare it before, but preceed it with the word "extern" and dont assign it a value. Example:

// Decleration in file1.cpp
int myVar = 32;

// external reference in file2.cpp
extern int myVar;

This tells your compiler that the variable exists, and what type it is so it can continue with compilation. The actual resolution of the variable then happens at link time when the linker evaluates the defined symbols in file1.o and file2.o.

Cheers!

Share on other sites
Example:
example.cpp
int someVariable = 0; // Variable to expose over translation units

example.h
extern int someVariable;  // Make the variable 'visible' to external units

any other file that needs to use the variable just needs to include the .h file and it should work just fine. Remember, the .h merely defines the actual variable as exposed extern-al. Point to remember: this kind of pollutes the global namespace so try not to abuse this.

Just fyi, 'extern' keyword is like a reminder to the compiler that a certain variable has been defined elsewhere. This instructs the compiler to delay actual references to the variable until it encounters it in later stages of linkage. Extern itself, however, does not create or initialize a variable in any way. If you are familiar with 'forward declarations' for classes and structures, then you can apply a somewhat similar logic here.

[Edit: Beaten to it :P]

Share on other sites
ah, i see. alright, thanks you too.

1. 1
2. 2
frob
15
3. 3
4. 4
5. 5

• 14
• 13
• 14
• 69
• 15
• Forum Statistics

• Total Topics
632138
• Total Posts
3004319

×