Multiple including a head file with a variable definition

后端 未结 4 676
野趣味
野趣味 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:55

    You are defining my_var once per compilation unit. Remember that include guards operate on a per compilation unit basis.

    To remedy, you should declare my_var as extern in the header:

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

    and define it in one of the source files using

    int my_var = 100;
    

    Then the linker sees only one definition and all will be fine.

提交回复
热议问题