1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Global variable C++ driving me nuts!!!!

Discussion in 'HTML, Graphics & Programming' started by JonD, 7 Feb 2006.

  1. JonD

    Wise Guy

    Joined: 26 Jun 2003

    Posts: 1,142

    Location: North West

    I have a variable:
    int view;

    and a few files:

    main.cpp
    main.h
    file1.cpp
    file1.h
    file2.cpp
    file2.h

    Now each file needs to access the one global copy of view, so I tried putting in a global.h file that is included on each header file above. Now I get the error:

    In file included from include/main.h:6,
    from src/main.cpp:17:
    include/globals.h:9: redefinition of `int view'
    src/main.cpp:15: `int view' previously declared here
    In file included from include/file1.h:9,
    from include/main.h:7,
    from src/main.cpp:17:
    include/globals.h:9: redefinition of `int view'
    include/globals.h:9: `int view' previously declared here

    Ive tried loads of combinations and I cant get it to stop giving me this error!

    Any ideas?
     
  2. dave_a141

    Gangster

    Joined: 9 May 2005

    Posts: 121

    Location: Yorkshire

    Have you put the preprocessor code to stop it including multiple versions?

    put somethings like this in the global.h

    at the beginning:
    Code:
    #ifndef _GLOBALH_
    #define _GLOBALH_
    
    then at the end of global.h
    Code:
    #endif
    
    This works most of time for me but if someone has a better way... :)
     
  3. Visage

    PermaBanned

    Joined: 13 Jan 2005

    Posts: 10,708

    Yup - sounds l;ike you need some include guards, as suggested.

    Global variables are a Bad Thing though - you should consider encapsulating them into a singleton class.....
     
  4. JonD

    Wise Guy

    Joined: 26 Jun 2003

    Posts: 1,142

    Location: North West

    I havnt put stuff into classes yet, but I will be.

    I forgot about that IFDEF stuff. Ill give that a try

    Thx