global variables in c++

This is a discussion on global variables in c++ within the C++ Programming forums, part of the General Programming Boards category; Hi, I was wondering how to create a variable in one file and then use it in all the files ...

  1. #1
    Registered User
    Join Date
    Nov 2007
    Posts
    11

    global variables in c++

    Hi,
    I was wondering how to create a variable in one file and then use it in all the files without the redeclaration of the variable with extern in every file that uses it.

    I have seen this so I know that it is possible but I don't know how it was implemented.

    Does anyone have a suggestion?

    Regards,
    Domen

  2. #2
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,920
    Make your global var in a .cpp file, then redeclare that variable in a header with "extern" before. Don't initalize it in the headerm though:

    Code:
    // in .cpp:
    int my_int = 50;
    // in .h:
    extern int my_int;

  3. #3
    Registered User
    Join Date
    Nov 2007
    Posts
    11
    Thanks for the quick reply. This was exactly what I was looking for

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 08-06-2008, 10:59 AM
  2. scope of global variables
    By laertius in forum C++ Programming
    Replies: 4
    Last Post: 10-15-2006, 02:59 AM
  3. global variables - okay sometimes...?
    By MadHatter in forum C++ Programming
    Replies: 21
    Last Post: 01-21-2003, 04:23 PM
  4. global variables
    By rdnjr in forum Linux Programming
    Replies: 0
    Last Post: 01-07-2003, 10:28 AM
  5. Global variables? Bad! Yes, but to what extent?
    By Boksha in forum C++ Programming
    Replies: 6
    Last Post: 05-26-2002, 05:37 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21