minyor
minyor

Reputation: 1037

Why do global variable get initialized by class in another source file?

For example, I have 2 sources with a class and a static function in each. Both classes, functions and global variables has same names: (I added functions only for comparision..)

//A.cpp
#include <stdio.h>

static bool FooFunc() { printf("Hello from function in A!\n"); return true; }

class FooClass
{
public:
    FooClass() { printf("Hello from class in A!\n\n"); }
};

static bool fooFunc = FooFunc();
static FooClass fooClass;

and

//B.cpp
#include <stdio.h>

static bool FooFunc() { printf("Hello from function in B!\n"); return true; }

class FooClass
{
public:
    FooClass() { printf("Hello from class in B!\n\n"); }
};

static bool fooFunc = FooFunc();
static FooClass fooClass;

Result:

Hello from function in A!
Hello from class in A!

Hello from function in B!
Hello from class in A!

Is class in 'B.cpp' gets ignored somehow? If so, shouldn't compiler give me some error or warning? I tried 'g++' and 'clang' compilers, same behavior.

Upvotes: 0

Views: 77

Answers (1)

KostasRim
KostasRim

Reputation: 2053

In c++ a source file is called a translation unit(after the preprocessor). After the compilation of each unit the object files (.o) are then linked together by the linker. Now each class has a unique identifier when it's linked(so it can be put together with other translation units, to resolve variables etc). Your source files have the same class names yielding to a violation of the one definition rule. So, you have two choices. First is to rename one of the two classes and second to put them under a namespace. Hope I helped.

Upvotes: 1

Related Questions