Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

sanamsadr

macrumors newbie
Original poster
Jan 17, 2009
1
0
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

macrumors newbie
Jan 26, 2009
1
0
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

Suspended
Nov 25, 2005
17,980
5,565
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.