Multiple including a head file with a variable definition

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

    The guard only prevents the header from being included twice in the same compilation unit.

    When you compile src1.o and src2.o, each one will contain a definition of my_var. When you link them to create a.out, the compiler cannot merge those definitions (even if they are identicals), and fails.

    What you want to do is declare my_var as extern :

    ---- head.h ----

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

    ---- my_var.c ----

    #include "head.h"
    
    int my_var = 100;
    

    Then compile all source files :

    g++ -c my_var.cpp -o my_var.o
    g++ -c src1.cpp -o scr1.o
    g++ -c src2.cpp -o src2.o
    g++ -o a.out my_var.o src2.o src1.o
    

    This way, my_var will be declared in every file, but will only be defined in my_var.o. There is an important difference here. Try to omit linking my_var.o, you'll see what the compiler has to say :)

提交回复
热议问题