using a string application-wide

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.
Last edited on
closed account (S6k9GNh0)
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.
Last edited on
how do i push it into the stack and pass the pointer around? i'm reading http://en.wikipedia.org/wiki/Stack_(data_structure) and i got no clue :S

edit: i think i found it :)

http://www.fredosaurus.com/notes-cpp/datastructs/ex1/usingstack.html

thanks!
Last edited on
You don't need that stack! He was talking about the internal stack that holds local variables.

Your need to make this variable global is an indication that you may have a bad program structure. If your code is not too long you should post it.
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:

extern string g_name;
Last edited on
beat me to my next question :)

thanks! thank you so much!
Last edited on
Topic archived. No new replies allowed.