Repeated Multiple Definition Errors from including same header in multiple cpps

后端 未结 9 1690
南方客
南方客 2020-11-27 06:12

So, no matter what I seem to do, I cannot seem to avoid having Dev C++ spew out numerous Multiple Definition errors as a result of me including the same header file in multi

9条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 06:54

    When you define a variable, the compiler sets aside memory for that variable. By defining a variable in the header file, and including that file into all your source files, you are defining the same variable in multiple files.

    Putting the keyword extern before a variable definition will tell the compiler that this variable has already been defined somewhere, and that you are only declaring (i.e. naming) the variable so that other files can use it.

    So in your header file you should make all your definitions forward declarations by adding the extern keyword.

    extern MYSTRUCT Job_Grunt;
    extern MYSTRUCT *Grunt;
    extern MYSTRUCT Job_Uruk;
    extern MYSTRUCT *Uruk;
    
    extern int Other_data[100];
    

    And then in one (and only one) of your source files, define the variables normally:

    MYSTRUCT Job_Grunt;
    MYSTRUCT *Grunt = &Job_Grunt;
    MYSTRUCT Job_Uruk;
    MYSTRUCT *Uruk = &Job_Grunt;
    
    int Other_data[100];
    

提交回复
热议问题