I've been trying to figure out some boundaries of g++
, especially linking (C++) object files. I found the following curiosity which I tried to compress as much as possible before asking.
Code
File common.h
#ifndef _COMMON_H
#define _COMMON_H
#include <iostream>
#define TMPL_Y(name,T) \
struct Y { \
T y; \
void f() { \
std::cout << name << "::f " << y << std::endl; \
} \
virtual void vf() { \
std::cout << name << "::vf " << y << std::endl; \
} \
Y() { \
std::cout << name << " ctor" << std::endl; \
} \
~Y() { \
std::cout << name << " dtor" << std::endl; \
} \
}
#define TMPL_Z(Z) \
struct Z { \
Y* y; \
Z(); \
void g(); \
}
#define TMPL_Z_impl(name,Z) \
Z::Z() { \
y = new Y(); \
y->y = name; \
std::cout << #Z << "(); sizeof(Y) = " << sizeof(Y) << std::endl; \
} \
void Z::g() { \
y->f(); \
y->vf(); \
}
#endif
File a.cpp
compiled with g++ -Wall -c a.cpp
#include "common.h"
TMPL_Y('a',char);
TMPL_Z(Za);
TMPL_Z_impl('a',Za);
File b.cpp
compiled with g++ -Wall -c b.cpp
#include "common.h"
TMPL_Y('b',unsigned long long);
TMPL_Z(Zb);
TMPL_Z_impl('b',Zb);
File main.cpp
compiled and linked with g++ -Wall a.o b.o main.cpp
#include "common.h"
struct Y;
TMPL_Z(Za);
TMPL_Z(Zb);
int main() {
Za za;
Zb zb;
za.g();
zb.g();
za.y = zb.y;
return 0;
}
The result of ./a.out
is
a ctor
Za(); sizeof(Y) = 8
a ctor // <- mayhem
Zb(); sizeof(Y) = 12
a::f a
a::vf a
a::f b // <- mayhem
a::vf b // <- mayhem
Question
Now, I would have expected g++
to call me some nasty names for trying to link a.o
and b.o
together. Especially the assignment of za.y = zb.y
is evil. Not only that g++
does not complain at all, that I want it to link together incompatible types with the same name (Y
) but it completely ignores the secondary definition in b.o
(resp. b.cpp
).
I mean I'm not doing something sooo far fetched. It is quite reasonable that two compilation units could use the same name for local classes, esp. in a large project.
Is this a bug? Could anybody shed some light on the issue?