Suppose in bar.h
there might exist:
static inline int fun () { return 2; }
And to ensure that fun
is always defined foo.h
contains the following:
static inline int fun () { return 3; }
Does the following elicit undefined behavior when bar.h
contains the definition?
#include "foo.h" /* ensure there is always a definition */
#include "bar.h" /* use the bar definition if it exists */
int main () {
/* ... */
int x = fun ();
/* ... */
With gcc (4.0.1) (old, but it's what I have currently) the behavior is as expected - the foo version is used when the bar version is missing and the bar version is used when it exists.
No, this is not allowed. Those definitions of
fun()
declarefun()
to have internal linkage (due to thestatic
), and §6.9 in the C standard says:Violation of a "shall" clause is undefined behaviour, which means that the semantics of your program are completely undefined, and the compiler doesn't have to issue an error message.
If you want to achieve the same effect, you can use a harmless macro:
Include order flips, but it's less scary than the full macro version (which isn't scary at all IMHO but I don't know your/your workplace's relationships with macros.)
You're not allowed to do that, and your compiler shouldn't let you.
You can have multiple definitions of a non-static inlined function only if all the definitions are identical (but never more than one definition per TU). This will necessarily happen for inlined functions defined in header files.
For static linkage each TU can have a different definition, but you can still only have one definition per TU.
(Sorry for the multiple edits.)