Multiple including a head file with a variable definition

后端 未结 4 727
野趣味
野趣味 2021-01-28 00:03

I just build a simple C++ project. The codes are shown in the follows:

-------- head.h --------

#ifndef _HEAD_H_
#define _HEAD_H_

int my_var = 100;

#en         


        
4条回答
  •  自闭症患者
    2021-01-28 00:44

    Change the header the following way

    #ifndef _HEAD_H_
    #define _HEAD_H_
    
    extern int my_var;
    
    #endif
    

    And for example add line in the module with main

    #include "head.h"
    int my_var = 100;
    int main() { return 0; }
    

    The problem is that as the header is included in two modules then each module contains a variable with external linkage with the same name as a variable in other module. And the linker does not know which variable to use.

提交回复
热议问题