Variable already defined in .obj; What is going on here?

后端 未结 6 1468
遇见更好的自我
遇见更好的自我 2021-01-20 09:43

head.h


#pragma once

namespace foo
{
    int bar;

    int funct1();
}

head.cpp

#include \"head.h\"

int foo::funct1()
{
         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-20 10:21

    Do carefully note that foo is not a class, but a namespace. When you declare a free variable in the header file:

    int bar;

    And then #include this header file multiple times (into different CPP files, causing multiple translation unit compilations), you'd get a linker error. Everyone knows it.

    And, you'd add extern attribute at the declaration, and define the variable elsewhere in one of the CPP/C file.

    Putting a global variable into a namespace is nothing but giving the global variable a different name. Think if foo::bar as foo__NS__bar, and hence you must add extern in the header and define foo::bar at some locatoin.

    Note that this is different from a non-static member variable of a class. A class variable doesn't need to be defined/declared this way since the class is a type. Each instantiated variable of class-type would have a separate copy of the variable. Further to that, when you add a static variable in the class, you are giving that logically global variable another name. Thence, you must have that static-variable defined one of the CPP file.

提交回复
热议问题