I have a program that has 1 main.cpp and 3 .h files.
one of the .h files gets the user's name (example code):
1 2 3
string name;
cout << "please enter your name";
cin >> name;
how would i go about using the string "name" application wide between all my header files and main.cpp? i have tried using &name but when i tried to use name in another function i got an error. Any help will be great, thanks.
You can push it to the stack and pass the pointer around. You can declare it extern. You can declare a variable in the header outside of a function scope. You can declare a variable outside of a function scope in the main.cpp.
I'm pretty sure they're other ways. Though to be honest, I've never used a global variable.
my codes way to long that was just an example before, but this is just part of the code that has little to do with the rest. as for structure, the rest of my program is really bad, i don't think one more bad thing will matter, i just need it done! ill do a google search about global variables and see if i can get that working. ty
The main idea about a global variable is that it must be declared (but not defined) everywhere it is used, but only actually defined once. So you should define it at the top of your main.cpp file, like this:
string g_name;
The prefix g_ is to remind us that it is global and to mitigate conflicts with other variable names.
Then in every other file that uses g_name, put this: