hello
I am trying to get variables that are global to multiple files. I have mananged to make constant variables that are global but maybe not in the best way. In the header i have the constant variables being defined: constint variable_Name = 5;
And the cpp file:
1 2 3 4 5 6 7 8 9 10
#include <iostream>
usingnamespace std;
#include "vars.h"
int main ( )
{
cout << variable_Name<< endl;
system ("pause");
return 0;
}
Is there a better way to do this and to make the variables able to be changed within the cpp files. thanks in advance
I'm not sure that I quite understand what you're saying, but try using extern:
1 2 3 4 5 6 7 8 9 10
// vars.h
#ifndef VARS_H // Do I even need an #include guard here? Oh well...
#define VARS_H
externint myInt;
externconstint myConstInt;
void doStuff(); // Does stuff with myInt
#endif
1 2 3 4 5 6 7 8 9 10 11
// vars.cpp
#include "vars.h"
// Some definitions, e.g.
int myInt = 4;
constint myConstInt = 7;
void doStuff()
{
myInt = 15; // Change myInt in this .cpp file
}
// main.cpp
#include <iostream>
#include "vars.h"
using std::cout;
void printVars()
{
cout << "myInt: " << myInt;
cout << "\nmyConstInt: " << myConstInt << std::endl;
}
int main()
{
cout << "Before doing anything:\n";
printVars();
doStuff();
cout << "\nAfter doing stuff (in the other .cpp file):\n";
printVars();
myInt = 100; // Change myInt here
cout << "\nAfter doing more stuff (in this .cpp file):\n";
printVars();
}
This will give you the output
Before doing anything:
myInt: 4
myConstInt: 7
After doing stuff (in the other .cpp file):
myInt: 15
myConstInt: 7
After doing more stuff (in this .cpp file):
myInt: 100
myConstInt: 7
> would i need to put it if functions were used instead of variables
functions declarations, no, it doesn't matter how many times a function is declared
functions definitions... ¿why do you have function definitions in a header?