强制内联函数在其他翻译单元 [英] force inline function in other translation unit
问题描述
在gcc手册的这一部分是pretty模糊,反复尝试后,我无法理解的forceinline属性的用法。
This part of the gcc manual is pretty obscure and i can't understand the usage of the forceinline attribute after repeated attempts.
我定义对象和特定功能来操纵该对象。很少有这些功能可以使用原子操作,我想编译器内联这些函数。但是我不想写这些函数在头文件,并用静态内联就像在Linux内核中声明它们。
I'm defining an object and certain functions to manipulate that object. Few of those functions can use atomic instructions and i want the compiler to inline those functions. However i do not want to write those functions in the header file and declare them with "static inline" like in the linux kernel.
有没有办法迫使GCC从另一个转换单元内联函数?
Is there a way to force gcc to inline functions from another translation unit ?
推荐答案
您可以使用 always_inline
属性,例如:
you can use the always_inline
attribute, for example:
void foo () __attribute__((always_inline));
从文档
always_inline
一般来说,除非指定优化功能不内联。对于函数声明为内联,此属性的内联
即使没有指定优化级别的功能。
always_inline Generally, functions are not inlined unless optimization is specified. For functions declared inline, this attribute inlines the function even if no optimization level was specified.
注1 :有没有必要使用在线
如果您使用 always_inline
属性
Note1: There's no need to use inline
if you use the always_inline
attribute
注2 :如果函数不能被内联,你会得到一个警告,例如,如果在编译时的定义不可用,但是,在一个更高的优化GCC还可以内联入呼叫者,有一个为太具体的开关:
Note2: If the function could not be inlined you will get a warning, if for example the definition is not available when compiling, however, at a higher optimization gcc can still inline it into the caller, there's a specific switch for that too:
-funit-at-a-time
从文档:
优化级别-O2以上,特别是,使
单位在-A-时间模式,其中的允许编译器要考虑的信息
编译函数时从文件后面的功能获得。
编译一次多个文件到一个输出文件
单位在-A-时间模式可让编译器使用从获得的信息
所有的文件汇编他们每个人当
Optimization levels -O2 and above, in particular, enable unit-at-a-time mode, which allows the compiler to consider information gained from later functions in the file when compiling a function. Compiling multiple files at once to a single output file in unit-at-a-time mode allows the compiler to use information gained from all of the files when compiling each of them.
注3 :
这是没有必要有一个明确的原型,因此您可以在功能确定指标使用属性:
Note3: It is not necessary to have an explicit prototype so you can use the attribute on the function defintion:
__attribute__((always_inline)) void foo() {
//some code
}
另请参阅此讨论,它回答大家的一些问题。
Also see this discussion, it answers some of your questions.
这篇关于强制内联函数在其他翻译单元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!