外部内联函数会发生什么? [英] What happens with an extern inline function?

查看:33
本文介绍了外部内联函数会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将 .h 文件中的函数定义为

extern int returnaint(void);

在相关的.c文件中定义为

inline int returnaint(void) {返回 1;}

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

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

解决方案

.c 文件的函数定义中添加 inline 是多余的.p>

  • .c 文件的编译单元看到一个 extern 声明(没有 inline)和一个 inline定义.因此它会在目标文件中发出函数的符号.

  • 所有其他编译单元只能看到 extern 声明,因此如果您将最终可执行文件与其他 .o 文件.

事实上,你只是用错了方法.此功能旨在用于您在 .h 文件中具有 inline 定义,对所有人可见.该函数的定义仅作为符号的声明,就像 extern 一样,但没有定义它.

extern 声明仅在一个 .c 文件(编译单元)中,然后确保在那里定义符号.

术语有点混乱,inline definition 充当符号的声明,而 extern declaration 作为它的定义

What happens if I define the function in my .h file as

extern int returnaint(void);

define it in the related .c file as

inline int returnaint(void) {
    return 1;
}

and include the header in another .c file and use the function? When I compile the things seperatly, creating a object file for each .c file and then link them, is the inlined function included, or what happens?

I know the compiler can ignore inline, but what if it does not ignore it in this case?

解决方案

Having added the inline to the function definition in the .c file is just superfluous.

  • Your compilation unit of the .c file sees an extern declaration (without inline) and an inline definition. Thus it emits the symbol for the function in the object file.

  • All other compilation units only see an extern declaration, and so they can use the function without problems, if you link your final executable with the other .o file.

In fact, you just have it the wrong way around. This feature is meant to be used that you have the inline defintion in the .h file, visible to everybody. This definition of the function only acts as a declaration of the symbol, just as extern would, but doesn't define it.

An extern declaration in just one .c file (compilation unit) then ensures such that the symbol is defined, there.

The terminology is a bit confusing, the inline definition acting as declaration of the symbol, and the extern declaration acting as definition of it

这篇关于外部内联函数会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆