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

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

head.h


#pragma once

namespace foo
{
    int bar;

    int funct1();
}

head.cpp

#include \"head.h\"

int foo::funct1()
{
         


        
6条回答
  •  时光取名叫无心
    2021-01-20 10:21

    I am not redefining anything. I am literally just assigning 1 to the variable

    You're redefining the variable!

    head.cpp has one via #include "head.h", and main.cpp has one via #include "head.h".

    You need to merely declare it (unusual but not too strange) in the header:

    extern int bar;
    

    …then define it in one translation unit. This is just like what you do with static class members (albeit with slightly different syntax).

    Since C++17, you may do this by instead plopping the inline keyword on to your definition.

    Alternatively, avoid mutable globals…

提交回复
热议问题