Reputation: 1841
I have a val.h
source code file with the global variable with internal linkage and inline function that returns its address:
// val.h
#pragma once
static int val;
inline int* get_val()
{
return &val;
}
Then this header is included in two different translation units. If I call &val
in both of these units, I get two different addresses, and it's ok since val
has an internal linkage and each translation unit has its own val
. But if I call get_val()
in both of these units, I get two equal addresses.
Is such behavior guaranteed by the standard, would we always obtain the same value returned by get_val()
call from any translation unit?
And what if compiler decides to make true inlining, i.e. just to replace get_val()
call by &val
statement in each translation unit. Would we get different addresses for each translation unit in such case?
Upvotes: 2
Views: 862
Reputation: 35164
As you have it you will get undefined behaviour when you include this header file in two different translation units. This is because expression return &val
will refer to two different objects; Thereby, the body of getVal
is different in both translation units, but getVal
has external linkage. So you violate the one definition rule.
To overcome this, you'd have to define internal linkage for getVal
, too, i.e. write static int* get_val() { ...
. Keyword inline
alone will not define external or internal linkage.
Upvotes: 1
Reputation: 66449
Your function violates the One Definition Rule since the expression val
refers to different entities in different translation units.
Its behaviour is undefined.
Upvotes: 4