Results 1 to 3 of 3

Thread: How to declare global variable outside a class?

  1. #1
    Join Date
    Apr 2010
    Location
    Singapore
    Posts
    156
    Thanks
    47
    Qt products
    Qt4
    Platforms
    Windows

    Question How to declare global variable outside a class?

    How to declare global variable outside a class?

  2. #2
    Join Date
    Jan 2006
    Location
    Belgium
    Posts
    1,938
    Thanked 268 Times in 268 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows
    Wiki edits
    20

    Default Re: How to declare global variable outside a class?

    Create a header with global definitions.

    Example: my_globals.h
    Qt Code:
    1. #ifndef MYGLOBALS
    2. #define MYGLOBALS
    3.  
    4. int variable1;
    5.  
    6. #endif
    To copy to clipboard, switch view to plain text mode 

    Include the header everywhere you want.

  3. #3
    Join Date
    Mar 2008
    Location
    France
    Posts
    149
    Thanks
    2
    Thanked 21 Times in 21 Posts
    Qt products
    Qt4
    Platforms
    Windows

    Default Re: How to declare global variable outside a class?

    Use extern keyword to avoid allocating some memory for yours global variables every time you include your header globalvar.h in multiple files. With this keyword you only allocate them once.
    Qt Code:
    1. // globalvar.h
    2.  
    3. #ifndef MYGLOBALS
    4. #define MYGLOBALS
    5.  
    6. extern int variable1;
    7. extern int variable2;
    8.  
    9. #endif
    10.  
    11. ...
    12.  
    13. // globalvar.cpp implementation
    14.  
    15. int variable1= 0;
    16. int variable = 0;
    To copy to clipboard, switch view to plain text mode 
    Last edited by toutarrive; 26th August 2010 at 10:33.

Similar Threads

  1. how to declare a global variable right
    By Cruz in forum Newbie
    Replies: 13
    Last Post: 16th February 2010, 17:25
  2. Replies: 2
    Last Post: 17th December 2009, 15:01
  3. global variable
    By Shuchi Agrawal in forum General Programming
    Replies: 10
    Last Post: 15th February 2007, 05:19
  4. is it legal to declare a pthread_t variable as local?
    By nass in forum General Programming
    Replies: 1
    Last Post: 14th February 2007, 14:27
  5. how to declare a friend variable ?
    By probine in forum General Programming
    Replies: 5
    Last Post: 27th March 2006, 16:00

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.