Page 1 of 1
seperating variables
Posted: Sat May 15, 2010 9:29 pm
by Randi
I want to separate my declaration of variables outside of my source document, is there a way of doing this that does not declare them as global, I know that I can do it by doing something like the following, but to my understanding doing this declares them as globals.
main
Code: Select all
#include "variables.h"
int main()
{
printf("x is at %d", x);
}
variables.h
Code: Select all
include "variables.cpp"
extern int x;
variables.cpp
Re: seperating variables
Posted: Sat May 15, 2010 10:22 pm
by RyanPridgeon
main
Code: Select all
#include "variables.h"
int main()
{
printf("x is at %d", x);
}
variables.h
Code: Select all
#ifndef VARIABLES_H
#define VARIABLES_H
extern int x;
#endif
variables.cpp
Code: Select all
#include "variables.h"
int x = 10;
If you don't want it global, you will have to pass it through functions and/or use classes and OOP.
Re: seperating variables
Posted: Sat May 15, 2010 11:10 pm
by X Abstract X
Use a namespace if you don't want to put it in a class.
Globals.h
Code: Select all
#ifndef GLOBALS_H
#define GLOBALS_H
namespace Globals {
const static double PI = 3.14159;
}
#endif
Main.cpp
Code: Select all
#include "Globals.h"
std::cout << 'PI = " << Globals::PI << "\n";
Re: seperating variables
Posted: Sun May 16, 2010 9:55 am
by dandymcgee
I saw this and immediately thought of Calculus.
A namespace seems like the best solution short of just making a class.
Re: seperating variables
Posted: Sun May 16, 2010 12:19 pm
by eatcomics
Yep, my rewrite of my game is doing away with Globals altogether hopefully
Re: seperating variables
Posted: Mon May 17, 2010 2:43 pm
by Randi
thanks for the help! namespaces work like a charm.
Re: seperating variables
Posted: Mon May 17, 2010 2:50 pm
by avansc
randi, look up what the variable qualifier "static" does, it may be something of interest.