best way to define global veriables in cpp

Hi all
just wonderd what is the best way to declair a veriabel accross multipel files in the same project.
for example in a game a currency system would need to be modifyable across the whole game on every file what is the most efficent way to acheve this.

thanks
for example in a game a currency system would need to be modifyable across the whole game on every file


That is false.

Global variables should be avoided, since they greatly restrict how the program can operate and they spread control over an excessively large area making bugs difficult to find.

If you write a function that uses a global variable... then that function can work with that one variable only. A better way to write the function would be to pass the variable as a parameter, then the function can work with ANY variable. This makes your code much more flexible.

Here's a simple example:

1
2
3
4
void damageplayer(int damage)
{
  playerlife -= damage;
}


This code harms the player, and seems simple enough. The problem is it is restrictive. What if you decide to add multiple players? Do you make another function?

1
2
3
4
5
6
7
8
9
void damageplayer1(int damage)
{
  player1life -= damage;
}

void damageplayer2(int damage)
{
  player2life -= damage;
}


What if there are 3 players? 4? What if there can be dozens? Do you keep adding new functions and changing each of them?



The better solution would be to pass the player/unit in question to the function:

1
2
3
4
int damageplayer(int playerlife, int damage)
{
  return playerlife - damage;
}


Now this one function can damage any player. It doesn't matter if you have one or a million. This function will work with all of them.
Thanks for the indepth answer I will try this out
If there is an instance where a variable needs to be declared globally, namespaces are probably your friends. Also the 'g' prefix helps to make things clear and to avoid duplicating label names. I like to use this method for defining global constants.

Header: (declare)
1
2
3
4
namespace Globals
{
    extern double gVariable1;
};


Source1: (define)
1
2
3
4
5
#include "header.h"
namespace Globals
{
    double gVariable1 = 1.;
};


Source2:
1
2
3
4
5
#include "header.h"
void MyFunc()
{
    Globals::gVariable1 += 4.0;
}


This will help to avoid confusion, but passing variables is still the best option when possible (which is almost always).
Last edited on
Topic archived. No new replies allowed.