Thread: single *.h in mutiple *.cpp

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    173

    single *.h in mutiple *.cpp

    hi guys:
    let's say, I have one *.h file and 4 *.cpp files.
    *.h file which named global.h. It contains all the variables and functions that the other *.cpp. as defined here, for example:
    #ifndef GLOBAL_H
    #define GLOBAL_H

    int Game_Start_Time = 0;

    #endif

    and the other 4 *.cpp files are player.cpp, enemy.cpp, weapons.cpp and main.cpp.

    I included global.h for every *.cpp file, but somehow I got such kind of error, Game_Start_time already defined in player.obj
    or enemy.obj or main.obj or weapons.obj.
    I just could not figure it out, someone could tell me please

    thanx alot.
    Don't laugh at me,I am just a SuperNewbie.

  2. #2
    Registered User
    Join Date
    Feb 2002
    Posts
    93
    why not just put all ur includes in a single .cpp


    -----------main.cpp-----------

    #include "player.cpp"
    #include "enemy.cpp"
    #include "weapons.cpp"
    #include "global.h"

    or

    ------------main.cpp-----------
    #include "global.h"
    ------------global.h------------
    #include "player.cpp"
    #include "enemy.cpp"
    #include "weapons.cpp"



    i don't believe u need all the #define, #endif... etc... if u include this way...hope this helps

  3. #3
    train spotter
    Join Date
    Aug 2001
    Location
    near a computer
    Posts
    3,868
    Global variables are different to say prototypes.

    Use the conditional comp (#ifndef as you have) for the macros and protos ect.

    For the global variables include the header in only in the main file and in the file you want to use the variable declare them as extern

    ie
    int iVar=0;//in global header

    extern int iVar;// in other files, note you can not reeinit the variables contents here
    "Man alone suffers so excruciatingly in the world that he was compelled to invent laughter."
    Friedrich Nietzsche

    "I spent a lot of my money on booze, birds and fast cars......the rest I squandered."
    George Best

    "If you are going through hell....keep going."
    Winston Churchill

  4. #4
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    I've learned that header files that are intended to be used by multiple cpp files should not have ANY variables in them. externs are the exception, however they aren't really an exception since they aren't really taking any memory by themself. They merely use memory that another object uses. You also want to watch out for putting "static" anything in a header file. I'm not telling you not to put these things into header files, but I am telling you to make sure that if you do make sure that only one c file includes that header.

Popular pages Recent additions subscribe to a feed