If I have a file foo.cpp
with the following code:
class Foo {
};
class Foo {
};
int main() {
return 0;
}
Then naturally I get error: redefinition of 'Foo'
. However, if I have foo.cpp
with
class Foo {
};
int main() {
return 0;
}
And bar.cpp
with
class Foo {
};
Despite class Foo
being defined twice across the program, this whole thing compiles fine.
If I had put int something;
in both files in global namespace, then I would've gotten a linker error (specifically duplicate symbol
), but for class definitions, this never happens.
I know function declarations such as int doIt();
can be duplicated in both cpp files, but a definition, e.g. int doIt() {}
cannot be. Now in the first compiler error (with class Foo{};
twice in one cpp file), it said redefinition of foo
, so class Foo{};
is a definition. Then why, unlike functions, can it be defined twice in one program?
EDIT: According to this website, named classes have external linkage. So why then is there no clash between class Foo
across both cpp files?
EDIT2: According to the website linked above, not only do named classes have external linkage, but so do it's static members. Yet this all compiles fine:
foo.cpp
:
class Foo {
public:
int foo();
static int x;
};
int Foo::foo() {
return 5;
}
int main() {
return 0;
}
bar.cpp
:
class Foo {
public:
int foo(int);
static bool x;
};
int Foo::foo(int i) {
return i * 2;
}
Not only has Foo::foo
been redefined with a different signature, but Foo::x
is of a different type. Both of these should have external linkage yet this code is A-ok.