0

What happens if member functions of a class in a header file are implemented in two cpp files which are both compiled by the compiler? I mean, lets say I have this code:

//header file A.hpp

class A
{
 public:
    int funcA();
}

//implementation file A1.cpp
#include "A.hpp"
int A::funcA(){/* whatever*/}

//implementation file A2.cpp
#include "A.hpp"
int A::funcA(){/* whatever*/}

Will the compiler trigger an error?

Nathan Pierson
  • 5,461
  • 1
  • 12
  • 30
  • 4
    This would be a violation of the [one definition rule](https://stackoverflow.com/questions/60085469/why-does-the-one-definition-rule-exist-in-c-c) – Nathan Pierson Aug 16 '22 at 13:56
  • 1
    ... and a violation of the ODR is Undefined Behavior. No error from the compiler is required. – Drew Dormann Aug 16 '22 at 13:58
  • 1
    This would be a linking error, if you attempt to link with both definitions. If you only link with one of them, there is no issue. – molbdnilo Aug 16 '22 at 13:58
  • 1
    *Will the compiler trigger an error?* **No**. There are many situations that are ill-formed code, where the compiler is not required to warn about the problem (**no diagnostic required**). On some systems, the **linker** may warn about the problem. – Eljay Aug 16 '22 at 14:05

1 Answers1

3

What happens if member functions of a class in a header file are implemented in two cpp files which are both compiled by the compiler?

It would be Undefined Behavior, as defined by the one definition rule.

Will the compiler trigger an error?

No. A compiler's job is to compile a single translation unit (a cpp file) and neither of your translation units violate this one definition rule.

The linker might inform you, but it is not required to do so. In the case of gcc, for example, ODR violations are only reported when link-time optimization is enabled.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180