Lately, I've been using more global variables declared in .cpp files instead of adding them as private class members. This way, I feel my classes can stay smaller, making them much easier to read. And since private members aren't accessible by other classes anyway, it seems to make sense not to put them in the 'public' header file.
I did notice that if I use the same variable name in two .cpp files, it counts as a duplicate variable definition.
So I'm wondering - is this ok? Is there a neater way to do it? Or should I really just use private class members?
Examples of usage are std::mutex variables, and arrays of resources that are loaded only once per application execution.
I did notice that if I use the same variable name in two .cpp files, it counts as a duplicate variable definition.
Yes, because they are externally linked and aceessible throughout your whole program.
First you should think if they needed to be global variables. If you still thing they should, you have several choices:
1) If they are logical part of some class, make them static variables of that class.
2) If you need to access them in other compilation units, place them into own namespace. That will have same result as having them to be public static members of class with same name (like how it is done in Java)
3) If you need to access them only in current file, place them into unnamed namespace.
4) For resources which need special handling make sure to access them throught special handler, maybe use Singletone pattern.
I did notice that if I use the same variable name in two .cpp files, it counts as a duplicate variable definition.
If you make the variable static or put it inside an unnamed namespace it will have internal linkage and will not be available to other translation units (.cpp files).
1 2 3 4 5 6
staticint global_var;
// or
namespace
{
int global_var;
}
Edit: removed unnecessary semicolon after namespace
These are some good tips, thanks very much. I think I misused the word global - my whole point is that they should only be visible in the current cpp file. An anonymous namespace or static keyword should work for me!