PDA

View Full Version : How to define a global variable in xcode?




sanamsadr
Jan 17, 2009, 01:13 PM
Hello all,

I am learning C++ on MAC using Xcode. I have a file .cpp and want to define a global variable xglob (for all the functions in that file). It seems so simple and all I should do (according to the manual I am following) is to put "int xglob" before "int main () ". but when I do that and use xglob even in the main() function, the compiler gives me the error message that :

"xglob was not declared in this scope". I have only "#include <iostream>" and "using namespace std" at the top of my simple program. I am stuck with this simple matter. Could you please help me resolve it?

Thanks.



mgates17
Jan 26, 2009, 08:19 PM
Sounds right. It would help if you posted a small sample code that exhibits the problem. This code works for me:

#include <iostream>
using namespace std;

int xglob;

int main( int argc, char* const argv[] )
{
std::cout << "Hello, World!\n";
std::cout << xglob << "\n";
return 0;
}

Though you should think twice before making global variables. They are useful, but also dangerous because you can't easily track who is accessing or changing it.

-mark

gnasher729
Jan 27, 2009, 03:40 AM
Though you should think twice before making global variables. They are useful, but also dangerous because you can't easily track who is accessing or changing it.

And if you use a global variable, it should be declared in the header file as well. If you don't access it from another file, it should be static.