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 behav开发者_StackOverflow中文版ior 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()
declare fun()
to have internal linkage (due to the static
), and §6.9 in the C standard says:
There shall be no more than one external definition for each identifier declared with internal linkage in a translation unit.
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.
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.)
If you want to achieve the same effect, you can use a harmless macro:
// foo.h - include guards omitted because of iPhone
#ifndef VALUE
# define VALUE 2
#endif
static inline int fun() { return VALUE; }
// bar.h
#define VALUE 3
#include "foo.h"
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.)
精彩评论