Global Variables
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 21

Thread: Global Variables

  1. #1
    Join Date
    Aug 2009
    Posts
    68

    Global Variables

    Hello,

    I'm having a little trouble understanding global variables. My project consists of a number of .h files, and a number of .cpp files. I have an integar variable, x, which I want to be able to use from all of my .cpp files. But where do I actually define x (for example "int x = 5"), such that this is possible? I have tried defining it just before my main function, in the global scope, but that does not work.

    I have also tried using the #define directive (for example "#define x 5") because I thought that if you use #define, then whatever you define will be accessible from all .cpp files. But this did not work either!

    I know this is a very simply problem, but it's confusing me!

    Thanks.

  2. #2
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,281

    Re: Global Variables

    Quote Originally Posted by karnavor View Post
    Hello,

    I'm having a little trouble understanding global variables. My project consists of a number of .h files, and a number of .cpp files. I have an integar variable, x, which I want to be able to use from all of my .cpp files. But where do I actually define x (for example "int x = 5"), such that this is possible? I have tried defining it just before my main function, in the global scope, but that does not work.

    I have also tried using the #define directive (for example "#define x 5") because I thought that if you use #define, then whatever you define will be accessible from all .cpp files. But this did not work either!

    I know this is a very simply problem, but it's confusing me!

    Thanks.
    Inside all your files, you have to declare that you are using this variable x (the compiler can't just guess). Further more, you have to say it isn't a new x either, and that it is defined elsewhere. This is where extern comes in.

    Like this

    Code:
    //file1.h
    
    extern int x;
    
    //other stuff
    Code:
    //file2.h
    
    extern int x;
    
    //other stuff
    Code:
    //somefile.h
     
     int x; actual declaration
     
     //other stuff
    Code:
    //somefile.cpp
      
      x = 5; actual initialization
      
      //other stuff
    Notice that file1.h and file2.h don't actually need to be told about some file. They just need to know the variable name, and that it is extern.

    If you don't want to write "extern int x;" in every file, the you should have a "common.h" file that contains general info that will be included everywhere anyways, and be more expandable (if one day you need a global y, you can just add it once in common.h)

    May I also add that it is usually considered bad design to use globals (not a rule, but generally). And if you are going to use globals, you may want to look into the "singleton" design pattern. Easier to use and maintain. Not every developer knows hows to manage a global. Every developer knows how to use static methods.

  3. #3
    Join Date
    Aug 2009
    Posts
    68

    Re: Global Variables

    Thanks, I tried defining the global variable in one .cpp file, and then declared the variable in my other .cpp files that need to reference it, using the extern keyword. However, I get the following error:

    "error LNK2001: unresolved external symbol"


    Any ideas?

  4. #4
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,281

    Re: Global Variables

    Quote Originally Posted by karnavor View Post
    Thanks, I tried defining the global variable in one .cpp file, and then declared the variable in my other .cpp files that need to reference it, using the extern keyword. However, I get the following error:

    "error LNK2001: unresolved external symbol"


    Any ideas?
    Not sure... I'd have to see some code, because I'm pretty confident what I told you was right, but not 100%. There could be pitfalls I'm unaware of.

    Post a complete but short example of your code that doesn't link correctly. We'd have more chances to help you.

  5. #5
    Join Date
    Aug 2009
    Posts
    68

    Re: Global Variables

    OK here is a sample code that demonstrates the problem:

    Code:
    // "myclass.h"
    
    class MyClass
    {
    	void MyFunction();
    };
    
    
    
    // "MyClass.cpp"
    
    #include "myclass.h"
    
    extern const int x;
    
    void MyClass::MyFunction()
    {
    	int y = x;
    }
    
    
    
    // "Program.cpp"
    
    const int x = 5;
    
    int main()
    {
    	return 0;
    }
    The error I am getting is:

    "error LNK2001: unresolved external symbol "int const x" (?x@@3HB) MyClass.obj"

    Thanks

  6. #6
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,247

    Re: Global Variables

    Quote Originally Posted by karnavor
    OK here is a sample code that demonstrates the problem:
    Read this again:
    Quote Originally Posted by monarch_dodra
    Inside all your files, you have to declare that you are using this variable x (the compiler can't just guess). Further more, you have to say it isn't a new x either, and that it is defined elsewhere. This is where extern comes in.
    Notice that Program.cpp does not have a declaration that x is extern.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  7. #7
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,281

    Re: Global Variables

    Quote Originally Posted by laserlight View Post
    Read this again:


    Notice that Program.cpp does not have a declaration that x is extern.
    Hey laserlight, is my example wrong? I was under the assumption tha at least one declaration of x was supposed to be without extern?

    I'm pretty sure karnavor so it could be me giving bad advice.

  8. #8
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,888

    Re: Global Variables

    Rule of thumb: Put the global variable in some (any) cpp file, and put the extern statements in h files.

    I'm assuming you're familiar with the admonition against global variables in general. It's somewhat less applicable when they're const, though.

  9. #9
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,281

    Re: Global Variables

    Quote Originally Posted by Lindley View Post
    Rule of thumb: Put the global variable in some (any) cpp file, and put the extern statements in h files.

    I'm assuming you're familiar with the admonition against global variables in general. It's somewhat less applicable when they're const, though.
    Do you have a link to the actual rules, rather than the "of thumb"?

  10. #10
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,247

    Re: Global Variables

    Quote Originally Posted by monarch_dodra
    Hey laserlight, is my example wrong?
    No, it is correct.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  11. #11
    Join Date
    Jun 2008
    Posts
    592

    Re: Global Variables

    How about globals are just dangerous?
    Read up on order of initialization across translation units( cpp files ). This goes very bad with classes. if you call a function that appends to a class that isn't initialized yet, you get some strange results....

    I suppose this will help you understand a bit better
    https://www.securecoding.cert.org/co...nslation+units
    0100 0111 0110 1111 0110 0100 0010 0000 0110 1001 0111 0011 0010 0000 0110 0110 0110 1111 0111 0010
    0110 0101 0111 0110 0110 0101 0111 0010 0010 0001 0010 0001 0000 0000 0000 0000
    0000 0000 0000 0000

  12. #12
    Arjay's Avatar
    Arjay is offline Moderator / MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    11,197

    Re: Global Variables

    Quote Originally Posted by monarch_dodra View Post
    Do you have a link to the actual rules, rather than the "of thumb"?
    You aren't really going to find a 'best practices' directive for this sort of thing.

    The reason is that while global variables were completely acceptable for C-style programs, they should be avoided for writing C++ programs because they break encapsulation and (as a result) are hard to debug.

    For C++ a more acceptable way to mimic global variables is to put variables that you wish to be global inside a class, instantiate a single instance of the class, and make the class global. So instead of having multiple globals variables floating around, there is only one (the class instance).

    An added benefit of this approach is that you can control the clean up of variables within a class because the cleanup code can be put inside a destructor (whereas with global variables you have to clean them up in a cleanup function and ensure that the function always gets called).

  13. #13
    Join Date
    Apr 1999
    Posts
    27,423

    Re: Global Variables

    Quote Originally Posted by Arjay View Post
    For C++ a more acceptable way to mimic global variables is to put variables that you wish to be global inside a class, instantiate a single instance of the class, and make the class global.
    Not only is that one acceptable way of doing this in C++, it is also an acceptable way of handling globals in 'C' (using a struct).

    Regards,

    Paul McKenzie

  14. #14
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,247

    Re: Global Variables

    Quote Originally Posted by Arjay
    The reason is that while global variables were completely acceptable for C-style programs, they should be avoided for writing C++ programs because they break encapsulation and (as a result) are hard to debug.
    Personally, I find that they make it harder to debug C programs too.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  15. #15
    Arjay's Avatar
    Arjay is offline Moderator / MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    11,197

    Re: Global Variables

    Paul and Laser - I agree.

    I don't code in C, so I didn't want to step on anyone's toes.

    Another benefit to putting the globals in a single class is when programming multithreaded programs.

    If you put the globals inside a class, you can also put thread synchronization code (i.e critical section or mutex) inside the class and expose the 'global variables' through accessor methods.

    By hiding the thread synchronization inside the class, consumers of the class don't need to worry about the locking/unlock threading business outside the class - they only need to know the class is threadsafe and don't need to concern themselves with 'how' it's threadsafe.

Page 1 of 2 12 LastLast

Posting Permissions

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


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center