Skip to main content
gamedev.net
🔒 Locked

Global variable? [Solved]

Started by polarboy Dec 24, 2008 at 8:44 PM 2 replies 1k views
Original Post
polarboy
polarboy
okay I got it, you just extern them below was my problem ---------------------------------- Hi, I'm working on my map editor for my game. and I have encountered problem with global variable I made two global variables: offsetx, offsety I have made my program to pass these variables to my functions, but I still want to know why it didn't work Here's what I did I put the global variables into a header include that header on my main.cpp my eventctrl.cpp would say these vars are not declared but if I include the header to eventctrl.cpp as well, the compiler tells me multiple declaration detected. In that sense, what's the point of a global variable -_- Is there ways around it? Or should I just stick to passing in variables to multple functions, or even better, classes~~ [Edited by - polarboy on December 24, 2008 9:05:52 PM]
oler1s
oler1s
Quote:
I put the global variables into a header
Define "put" global variables in a header. What does that mean?

In any case, consider googling how to declare variables. Declare, not define.
polarboy
polarboy
Quote:
Original post by oler1s
Quote:
I put the global variables into a header
Define "put" global variables in a header. What does that mean?

In any case, consider googling how to declare variables. Declare, not define.


meaning putting declaration inside a header

ie int offset_x = 0;
WhatsUnderThere
WhatsUnderThere
The typical way I do global variables is as follows:

//globals.hppnamespace global{   extern int my_var;}//globals.cpp#include "globals.hpp"int global::my_var = 500;//main.cpp#include <iostream>#include "globals.hpp"int main(){   global::my_var++;   std::cout << global::my_var << std::endl;    //prints out 501}


Just include globals.hpp in any files that need access to your global variables. Make sure your extern'd globals are only instantiated once, preferably all in a single file such as globals.cpp. Also, you would probably want to make the globals constant in this case.

Topic Locked

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

Sign in to reply to this topic.