Skip to main content
GameDev.net gamedev.net
🔒 Locked

C++ CPP-wide vars

Started by Paul-K Mar 31, 2011 at 11:12 AM 0 replies 900+ views
Original Post
Paul-K
Paul-K
Hello all,
I'm trying to make a simple multiplayer thingy (nothing usefull but just to try to achieve something). Now, first I had everything packed together into main.cpp but that of course, is selfkill

Now, I tried to breakt he code up and place it into other cpp files. I came quite far with it but walking into some problems now.

Example: I got a file tools.cpp which includes:

void paintBox(int fromX,int fromY,int pNum){
HBRUSH blueBrush=CreateSolidBrush(RGB(0,0,255));
HBRUSH redBrush=CreateSolidBrush(RGB(255,0,0));
HBRUSH greenBrush=CreateSolidBrush(RGB(0,255,0));
HBRUSH yellowBrush=CreateSolidBrush(RGB(255,255,0));
HBRUSH purpleBrush=CreateSolidBrush(RGB(255,0,255));

HBRUSH painter;
hDC = GetDC(mainWindow);
RECT rect;
rect.left = fromX;
rect.top = fromY;
rect.right = fromX+32;
rect.bottom = fromY+32;

switch(pNum){
case 0:painter = blueBrush;break;
case 1:painter = redBrush;break;
case 2:painter = greenBrush;break;
case 3:painter = yellowBrush;break;
case 4:painter = purpleBrush;break;

}
FillRect(hDC,▭,painter);
ReleaseDC(mainWindow,hDC);
}


Now of course, the problem occurs that mainWindow and hDC are undefined. Now, I tried to put these things in a .h (LIKE HWND mainWindow;) but that gives linking errors.
How should I solve this? Is there a way to make vars 'global' to assign them in a file (like main.cpp) and make them usable by all other cpp files.
Also, I got a player class and a player var, including position etc, but the updating off this will happen in another cpp file(data handler), there you want to do players[playerNum].setPos(1,5);

Thanks in advance!

Paul
the_edd
the_edd

// in mainwindow.h

extern HWND mainWindow; // declaration


and then


// in mainwindow.cpp

HWND mainWindow; // definition


Now #include "mainwindow.h" in all source files that need access to the mainWindow variable.

Or, don't use a global variable and pass in the window handle to paintBox(). This is a much better option, I'd say.

For your "players" stuff: again, much better if you can avoid global variables. The argument-passing/function-call chain helps to track function side effects. Global variables don't.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.