Global variables for multiple cpp files

closed account (96AX92yv)
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:
const int variable_Name = 5;
And the cpp file:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace 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

extern int myInt;
extern const int 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;
const int myConstInt = 7;

void doStuff()
{
    myInt = 15; // Change myInt in this .cpp file
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 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
closed account (96AX92yv)
Thanks, can you explain what the #ifndef VARS_H and #define VARS_H is for?
It's basically just to prevent the file from being #include d multiple times.
http://www.cplusplus.com/forum/articles/10627/#msg49679
closed account (96AX92yv)
would i need to put it if functions were used instead of variables
I would just go ahead and put them in all of your header files.
It doesn't hurt either way....
closed account (96AX92yv)
Thanks for your help
> 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?

(especial case: inline and template http://www.cplusplus.com/forum/general/113904/#msg622073 )
Topic archived. No new replies allowed.