I need to set a variable in the main function and access it from a different function in the same file. I can not pass it to the function because it means changing the entire code structure, which is not an option. To avoid declaring a global variable I crated a namespace and I want to check if this is a good programming practice or is there a cleaner way to do it. This is the code:
namespace mylocalnamespace{
int myglobalvar;
}
static void myFunc()
{
..... some code
operationX(mylocalnamespace::myglobalvar);
..... some code
}
int main(int argc, char **argv)
{
..... some code
mylocalnamespace::myglobalvar = atoi(argv[0]);
..... some code
}
Alternatives To Global Variables in C++
In the example, function argument is a good alternative to avoid a global variable:
static void myFunc(int mylocalvar)
{
..... some code
operationX(mylocalvar);
..... some code
}
int main(int argc, char **argv)
{
..... some code
mylocalvar = atoi(argv[0]);
..... some code
myFunc(mylocalvar);
}
I can not pass it to the function
Oh well, then you have to use a global variable.
Since you apparently use it in a function with internal linkage, you could improve slightly by using global with internal linkage as well. This way the global won't leak to other translation units. A handy way to achieve that is an anonymous namespace:
namespace {
int myglobalvar;
void myFunc() {
// ...
To avoid declaring a global variable I crated a namespace
Global variables are still global variables even if not in the global namespace.