How to define a global variable in xcode?

Discussion in 'Mac Programming' started by sanamsadr, Jan 17, 2009.

  1. macrumors newbie

    Joined:
    Jan 17, 2009
    #1
    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.
     
  2. macrumors newbie

    Joined:
    Jan 26, 2009
    #2
    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
     
  3. macrumors G5

    gnasher729

    Joined:
    Nov 25, 2005
    #3
    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.
     

Share This Page