C:指向内联函数的指针
我在 H 文件中定义了一个静态内联函数,并且在 C 文件中的某一时刻,我为该函数分配了一个指针,如下所示:
foo.h:
static inline void frobnicate(void) {
// frobs something.
}
foo.c
#include "foo.h"
void execute(void (*func)(void) ) {
func();
}
void blahBlahBlah(void) {
execute(frobnicate);
}
bar所以
#include "foo.h"
// ...
frobnicate();
我认为这里会发生的是,编译器将从 bar.c 内联对 frobnicate
的调用,但在 foo.c 中,它实际上必须创建一个函数来实现 frobnicate
,这样它可以有一个指向它的工作指针。
谁能确认我的理解是否准确,并纠正我?
I have a static inline
function defined in an H file, and at one point in a C file, I'm assigning a pointer to the function, something like this:
foo.h:
static inline void frobnicate(void) {
// frobs something.
}
foo.c
#include "foo.h"
void execute(void (*func)(void) ) {
func();
}
void blahBlahBlah(void) {
execute(frobnicate);
}
bar.c
#include "foo.h"
// ...
frobnicate();
So I think what will happen here is that the compiler will inline the call to frobnicate
from bar.c, but in foo.c, it will actually have to create a function to implement frobnicate
, so that it can have a working pointer to it.
Can anyone confirm if my understanding is accurate, and correct me otherwise?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
inline
是 C 标准的误称之一。它的主要意义是能够将函数的定义放在头文件中,而不必在链接时处理“多重定义”问题。C99 和 C11 中实现您想要实现的目标的官方方法是在头文件中包含
inline
定义,而不使用static
。由于您还需要发出符号,因此您需要告诉编译器这应该位于哪个编译单元中。这样的实例化可以通过在 .c 文件中添加一个声明来完成,其中省略inline
关键字。最自然地,您可以在实际需要符号的地方使用 .c 文件。
inline
is one of the misnomers of the C standard. Its main meaning is to be able to put the definition of a function in a header file without having to deal with "multiple definition" problems at link time.The official way in C99 and C11 to do what you want to achieve is to have the
inline
definition in the header file, without thestatic
. Since you also need the symbol to be emitted you need to tell the compiler in which compilation unit this should be. Such an instantiation can be done by have a declaration in that .c file where you omit theinline
keyword.Most naturally you could use the .c file where you actually need the symbol.
是的你是对的。当您获取指向函数的指针时,编译器必须创建一个“独立”版本,其中代码可以作为普通函数调用。
内联函数的好处是不需要创建调用代码,并且可以应用任何其他优化来集成调用函数和内联函数。但是,当您需要定期调用该函数时(例如当您获取地址来稍后调用它时),这些优化就不再可能了。
Yes, you are right. When you take the pointer to the function the compiler must create an "stand alone" version where the code can be called as a normal function.
The benefit of inlining a function is that the calling code need not to be created and any other optimization can be aplied to integrate both the caller function and the inlined function. But when you need to do a regular call to the function(as when you take the address to call it latter), those optimizations are not possible anymore.