C static inline function redefinition rules

元气小坏坏 提交于 2019-12-22 22:25:47

问题


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.


回答1:


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.




回答2:


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.)




回答3:


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.)



来源:https://stackoverflow.com/questions/6448276/c-static-inline-function-redefinition-rules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!