Pol
Pol

Reputation: 325

Inline functions with same type but different body in .cpp files

A bit of a weird one and not very practical, but I'm trying some random things with inline in cpp and I thought about trying this:

 inline void foo(void){static int x=0; x++; cout << x << '\n'; return;};

and in another .cpp file I've got:

 inline void foo(void){static int x=0; x=x+2; cout << x << '\n'; return;};

Now, this works for some reason( same function type/name) but the different body, they both share the same 'x' but their definition is not the same. I would expect the compiler to complain, but it's not. why is that?

Upvotes: 2

Views: 487

Answers (2)

user12002570
user12002570

Reputation: 1

The program is ill-formed no diagnostic required as per basic.def.odr#13:

  1. There can be more than one definition of a
  • inline function or variable ([dcl.inline]),

in a program provided that each definition appears in a different translation unit and the definitions satisfy the following requirements. Given such an entity D defined in more than one translation unit, for all definitions of D, or, if D is an unnamed enumeration, for all definitions of D that are reachable at any given program point, the following requirements shall be satisfied.

  • Each such definition shall consist of the same sequence of tokens, where the definition of a closure type is considered to consist of the sequence of tokens of the corresponding lambda-expression.
  1. If these definitions do not satisfy these requirements, then the program is ill-formed; a diagnostic is required only if the entity is attached to a named module and a prior definition is reachable at the point where a later definition occurs.

(emphasis mine)

And since the function definitions in your example does not consist of the same sequence of tokens, the program is ill-formed no diagnostic required.

Upvotes: 3

Zig Razor
Zig Razor

Reputation: 3495

You are falling in an undefined behaviour.

The compiler does not say nothing because:

Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program outside of a discarded statement; no diagnostic required. The definition can appear explicitly in the program, it can be found in the standard or a user-defined library, or (when appropriate) it is implicitly defined (see [class.ctor], [class.dtor] and [class.copy]). An inline function or variable shall be defined in every translation unit in which it is odr-used outside of a discarded statement.

more details about that here and in the cppreference site

Upvotes: 2

Related Questions