Search code examples
c++variablesc++14declarationdefinition

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


head.h


#pragma once

namespace foo
{
    int bar;

    int funct1();
}

head.cpp

#include "head.h"

int foo::funct1()
{
    return bar;
}

main.cpp

#include <iostream>

#include "head.h"


int main()
{
    foo::bar = 1;
    std::cout << foo::funct1() << std::endl;
    return 0;
}

Error LNK2005 "int foo::bar" (?bar@foo@@3HA) already defined in head.obj

I don't understand what is going on. I tried looking for the answer but everyone's questions are so specific to their code and don't even look close to the problem that I am having.

I am not including .cpp files into main. I am not redefining anything. I am literally just assigning 1 to the variable then returning it with a function in the same namespace. How is it being defined multiple times?


Solution

  • The header head.h is included in two compilation units head.cpp and main.cpp. So the variable bar is defined twice. You could declare the variable without its definition the following way

    #pragma once
    
    namespace foo
    {
        extern int bar;
    
        int funct1();
    }
    

    and then define it in some cpp module.