CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: Global variable

  1. #1
    Join Date
    Jul 1999
    Location
    France
    Posts
    66

    Global variable

    hello, i made an int variable named "My_var"

    i want to acces to it from all my classes, how can i do ?


  2. #2
    Join Date
    Jun 1999
    Posts
    315

    Re: Global variable

    you'll need to extern it to every file that will use it:

    in file1.cpp

    int My_Var;




    if file2.cpp that will use My_Var

    extern int My_Var;




    miked

  3. #3
    Join Date
    May 1999
    Posts
    37

    Re: Global variable

    Hi

    Make it global, i.e. declare it outside any class in a .h file or in a dedicated .h file. Place extern int MyVar in cpp file where you need this variable. Or place this statement in a dedicated .h file. You must only be sure that you DECLARE your variable once.

    HTH

    Yves Le Sant
    Metrology and Measurement Unit
    Fundamental and Experimental Aerodynamics Departement
    ONERA Meudon
    (Office National d'Etudes et de Recherches Aérospatiales)
    FRANCE

  4. #4
    Join Date
    Jul 1999
    Location
    Uitca, NY
    Posts
    120

    Re: Global variable

    The extern keyword does not redefine the variable. It tells the compiler to look elsewhere for the variable declaration. One more item about global variables: if you have a local variable of the same name, then within that function calling that name will refer to the local variable. To access the global variable use the scope resolution operator ::. If you always use the scope resolution operator to access a global then you can easily identify globals in your code.

    In file pair MyClass1.cpp/MyClass1.h:

    int nMyInt; // global variable

    void MyFunction()
    {
    int nMyInt; // local variable
    nMyInt = 1; // assign 1 to local variable
    ::nMyInt = 2; // assign 2 to global variable
    }



    In file pair MyClass2.cpp/MyClass2.h:

    extern int nMyInt;





  5. #5
    Join Date
    Jul 1999
    Location
    France
    Posts
    66

    Re: Global variable

    thank you all, it's a very good help



Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured