所有对内联函数的调用都必须重新编译吗?
我需要知道这个东西是如何工作的?我的意思是“所有对内联函数的调用都必须重新编译”。我正在读一本书,其中说每次在我们的程序中使用内联函数时,编译器都会重新编译短函数定义并将此编译后的短定义的副本放入代码中。
我根本不明白这一点。如果能用示例说明整个过程,我们将不胜感激。另外,您能解释一下它是如何提高效率的吗?
多谢。
I need to know how does this thing work? By this i mean " all calls to an inline function must be recompiled". I am reading a book which says that each time the inline function is used in our program, the compiler will recompile the short function definition and place a copy of this compiled short definition in your code.
I don't understand this at all. An explanation with example showing the whole proces will be highly appreciated. Also, could you please explain how does it improve the efficiency.
Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设你有这样的代码:
如果
foo
是内联的,那么编译器基本上会将代码重写为:现在,如果不是
bar();
你有一个更复杂的片段代码,那么该代码段将出现(并被编译)三次,而不是一次。您可以用函数调用的成本来换取增加和重复的代码。
编译器很可能拒绝实际内联函数。如果您曾经获取 foo 的地址并将其传递到外部某个地方,您甚至无法绕过创建独立版本。在实践中,独立和内联的完美组合将会发生,具体取决于最适合的。 (不过,对于最终生成的代码来说,更重要的是 inline 关键字对单一定义规则的影响。)
Suppose you have this code:
If
foo
is inlined, then the compiler will essentially rewrite the code as:Now if instead of
bar();
you had a more complex piece of code, then that piece of code would appear (and be compiled) three times, rather than just once.You trade the cost of a function call against increased and repetitive code.
The compiler may well refuse to actually inline a function. If you ever take the address of
foo
and pass it somewhere outside, you cannot even get around creating a stand-alone version. In practice, a happy mix of standalones and inlining will happen, depending on what fits best. (More important to what code ends up being generated is the effect of theinline
keyword on the one-definition rule, though.)内联函数获取代码并在使用它的任何地方插入一个副本(因此是内联) - 这节省了函数调用的成本。
显然,如果您更改函数,则必须在使用该函数的所有地方更改副本 - 并且每个文件(或代码块)都必须重新编译
An inline function takes the code and inserts a copy everywhere it is used (hence inline) - this saves the cost of a function call.
Obviosuly if you change the function then the copy must be changed everywhere it is used - and each of those files (or code blocks) must be recompiled
来自维基百科
http://en.wikipedia.org/wiki/Inline_function
这意味着编译器将扩展对函数定义的内联函数调用。换句话说,函数的完整主体在调用的每个地方都会被替换。
而对于普通函数,函数定义保存在一个位置,并且每当在代码中调用函数时,编译器都会生成代码来调用该函数。
另请注意,将函数指定为内联只是一个请求,编译器也应忽略此请求。
From Wikipedia
http://en.wikipedia.org/wiki/Inline_function
This means compiler will expand the inline function call to function definition. In other words the complete body of the function is replaced in every place the call is made.
Whereas for a normal function, the function definition is kept in one place and, compiler generates code to call the function whenever function is called in your code.
Also note that specifying a function as inline is only a request and compilers shall ignore this request too.