Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is no linker error while defining classes with the same name in two different cpp files?

Tags:

c++

linker

everyone!

Please consider the following peace of code:

   $ cat a.cpp
   #include <stdio.h>

   struct A
   {
      void foo() { printf("a.cpp: A::foo()\n");}
   };

   void fooA()
   {
      A a;
      a.foo();
   }

   $ cat b.cpp
   #include <stdio.h>

   struct A
   {
      void foo() { printf("b.cpp: A::foo()\n");}
   };

   void fooB()
   {
      A a;
      a.foo();
   }

   $ cat main.cpp 
   void fooA();
   void fooB();

   int main()
   {
         fooA();
         fooB();
         return 0;
   }

   $ g++ main.cpp a.cpp b.cpp 

   $ ./a.out
   a.cpp: A::foo()
   a.cpp: A::foo()

As you can see there is no warnings or errors from linker, but on runtime we receive not what we expected. I check it on gcc 4.8.1 and msvc 2013. With simple free functions linker will raise an error in such case. But if it a method of the class it doesn't.

Why it works like this?

like image 735
Denis Bakhvalov Avatar asked Jun 04 '26 14:06

Denis Bakhvalov


1 Answers

Functions defined inside a class definition are implicitly inline, so you're allowed to define them in multiple translation units.

The definitions must be identical, but the compiler isn't required to diagnose that since it that would be impossible when processing one unit at a time. You broke that rule, giving undefined behaviour.

To use the same name for different entities in different translation units, you could put each in a different namespace, or an unnamed namespace which is local to the translation unit:

namespace /* optional name */ {
    class A {
        // whatever you want
    };
}
like image 61
Mike Seymour Avatar answered Jun 06 '26 07:06

Mike Seymour