Reputation: 49339
I am using C++ as intermediate language, for each function object I am creating a unique class with a call method. What I am avoiding is checking if a similar function is already used and its corresponding class defined, so I may end up with exact same class with a different name. So I am wondering if compiler (g++) will detect this and merge classes.
Upvotes: 1
Views: 215
Reputation: 2615
Just to clarify on both previous answers (which are good answers):
The compiler will absolutely not merge your classes, at all. Some linkers might have some optimizations along those lines, but it's by no means a standard feature and neither the standard Microsoft nor GNU/Linux linkers do that. Usually the linker will only do that if you emit weak entries with the same name in the object files directly, which is what happens with template instantiations for instance. There is no standard way to obtain this behavior in C/C++ directly, although at least GCC offers extensions to control this linking yourself.
You should do it yourself though because it actually is an optimization. Jason is right that it would "just" cut down on code size, but on modern PC architectures that is itself a huge optimization. The code caches on the CPU aren't getting much bigger and memory speeds are nowhere close to CPU speeds, so cache misses caused by having an overly huge code image can have very serious performance impacts. There are benchmarks showing that compiling the Linux kernel or large apps like Firefox or OpenOffice with -Os (optimize for size) is faster in some workloads by a wide margin than when compiled with -O3.
Upvotes: 2
Reputation: 32538
No, at least g++ won't, because a class defines a namespace, so a function in class A
is actually not the same as a function in class B
even if the function itself has the same name. For example, A::foo()
is not the same as B::foo()
.
Also in the object file created after compilation, the function names are mangled, so A::foo()
won't have the same literal name as B::foo()
even though there is no namespace abstraction at the compiled object file level. So the linker is not going to be able to weed out functions from two different C++ classes based on their names.
Upvotes: 1
Reputation: 57794
I doubt it will. That would be difficult to detect in the general case, and there is no runtime efficiency in optimizing it. The only savings would be code space. An optimizing linker might perform such a transformation, but those are rare in the wild.
Upvotes: 0