Multiple including a head file with a variable definition

后端 未结 4 679
野趣味
野趣味 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 01:08

    your problem boils down to understanding C++ storage classes; static and extern more precisely.

    extern says: this variable is defined in a different file, this 
                 is only a declaration
    static says: this variable's lifetime is the program lifetime and
                 restrict it's visibility to the current file. 
    
    
    
    What happens in your case:
       - each file includes the variable declaration and definition `int my_var = 100;`,
         so both object scr1.o and scr2.o will contain the variable definition. When
         linking them, the linker cannot solve the ambiguity and throws an error.
       - adding the extern qualifier and defining the variable in one of the files 
         solves this problem: in one source it'll be an external unresolved at compile
         time, symbol and the other will contain the actual symbol.
    

    As for the second part of your question; why adding static seems to help the linker. Look at what I just said about static storage class: basically each object will have their own copy of the variable - not the same one!

提交回复
热议问题