mardi 28 juin 2016

Why does a member function exist only once even defined in one multiple included .h file?

I am just wondering how the compiler can handle the situation where a member function is declared & defined only in a include file but this .h file is included multiple times in different source codes without complains of the linker regarding multiple definition of ....

foo_1.h:

class foo
{
public:
    auto in_include() -> void { printf( "in in_include()\n" ); }
    foo();
};

foo_1.cpp:

#include <stdio.h>
#include "foo_1.h"

foo::foo()
{
        printf( "in foo()\n" );
        in_include();
}

and finally foo_main.cpp:

#include <stdio.h>
#include "foo_1.h"

int main()
{
        foo fooObject;
}

These MCVE compiles and links fine and produces the expected output:

in foo()
in in_include()

BUT, when I add in foo_1.h this line int globar_var; then the linker complains [as I expect it]:

/tmp/ccfjJJAT.o:(.bss+0x0): multiple definition of `globar_var'
/tmp/cciob9sM.o:(.bss+0x0): first defined here

Aucun commentaire:

Enregistrer un commentaire