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

Viewed 131

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?

1 Answers

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

Related