外部内联函数会发生什么?

前端之家收集整理的这篇文章主要介绍了外部内联函数会发生什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我将.h文件中的函数定义为
extern int returnaint(void);

,将相关的.c文件定义为

inline int returnaint(void) {
    return 1;
}

并将标题包含在另一个.c文件中并使用该函数?当我单独编译这些东西时,为每个.c文件创建一个对象文件,然后链接它们,是否包括内联函数,或者会发生什么?

我知道编译器可以忽略内联,但是如果在这种情况下不会忽略它呢?

解决方法

它不会编译.来自C11(ISO / IEC 9899:2011)§6.7.4功能说明符(加重点):

Any function with internal linkage can be an inline function. For a function with external
linkage,the following restrictions apply: If a function is declared with an inline function specifier,then it shall also be defined in the same translation unit. If all of the
file scope declarations for a function in a translation unit include the inline function
specifier without extern,then the definition in that translation unit is an inline
definition. An inline definition does not provide an external definition for the function,
and does not forbid an external definition in another translation unit. An inline definition
provides an alternative to an external definition,which a translator may use to implement
any call to the function in the same translation unit. It is unspecified whether a call to the
function uses the inline definition or the external definition.140)

140)Since an inline definition is distinct from the corresponding external definition and from any other
corresponding inline definitions in other translation units,all corresponding objects with static storage
duration are also distinct in each of the definitions.

另一个.c文件只能从头文件获取内联函数的声明,而不是定义,因此它符合粗体字的规则.

编辑:

正如@Jens Gustedt指出的,我以前的解释是错误的,因为在OP的问题中,该函数在头文件中被声明为非内联:

extern int returnaint(void);

所以其他的.c文件会像普通的函数一样对待它.

原文链接:/c/113181.html

猜你在找的C&C++相关文章