为什么将 C 函数声明为静态内联函数? [英] Why declare a C function as static inline?

查看:111
本文介绍了为什么将 C 函数声明为静态内联函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个声明为 C 函数的示例:

I came across an example for a C-function declared as:

static inline CGPoint SOCGPointAdd(const CGPoint a, const CGPoint b) {
    return CGPointMake(a.x + b.x, a.y + b.y);
}

到目前为止,我在 .h 文件中声明了实用程序 C 函数并在 .m 文件中实现了它们,就像这样:

Until now, I declared utility C-functions in .h files and implemented them in .m files, just like this:

CGPoint SOCGPointAdd(const CGPoint a, const CGPoint b) {
    return CGPointMake(a.x + b.x, a.y + b.y);
}

我可以在任何我想要的地方内联"使用这个函数,它也应该是静态的",因为它不与任何对象相关联,比如 Objective-c 方法.指定静态"和内联"的要点/优势是什么?

I can use this function "inline" anywhere I want and it should also be "static" because it's not associated with any object, like an Objective-c method. What is the point / advantage of specifying "static" and "inline"?

推荐答案

inline 并不意味着你可以使用inline"函数(在其他函数内部使用函数是正常的;你不需要 inline );它鼓励编译器将函数构建到使用它的代码中(通常是为了提高执行速度).

inline does not mean you can use the function "inline" (it is normal to use functions inside other functions; you do not need inline for that); it encourages the compiler to build the function into the code where it is used (generally with the goal of improving execution speed).

static 表示函数名没有外部链接.如果函数没有声明为static,则编译器需要使其外部可见,以便它可以与其他目标模块链接.为此,编译器必须包含一个单独的非内联函数实例.通过声明函数 static,您允许它的所有实例都内联在当前模块中,可能不会留下单独的实例.

static means the function name is not externally linked. If the function were not declared static, the compiler is required to make it externally visible, so that it can be linked with other object modules. To do this, the compiler must include a separate non-inline instance of the function. By declaring the function static, you are permitting all instances of it to be inlined in the current module, possibly leaving no separate instance.

static inline 通常与在调用例程中完成的小函数一起使用,而不是使用调用机制,仅仅因为它们又短又快,实际执行它们比调用单独的副本.例如:

static inline is usually used with small functions that are better done in the calling routine than by using a call mechanism, simply because they are so short and fast that actually doing them is better than calling a separate copy. E.g.:

static inline double square(double x) { return x*x; }

这篇关于为什么将 C 函数声明为静态内联函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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