c++ - header 中定义的 C++ 类方法是否始终内联?

标签 c++ header linker

Edit: I've restored the original title but really what I should have asked was this: 'How do C++ linkers handle class methods which have been defined in multiple object files'

假设我在头文件中定义了一个 C++ 类:

class Klass
{
    int Obnoxiously_Large_Method()
    {
        //many thousands of lines of code here
    }
}

如果我编译一些在多个位置使用“Obnoxiously_Large_Method”的 C++ 代码,生成的目标文件是否始终内联“Obnoxiously_Large_Method”的代码,或者它是否会针对大小进行优化(例如,在使用 g++ -Os 时)并创建一个'Obnoxiously_Large_Method' 的单个实例并像普通函数一样使用它?如果是这样,链接器如何解决实例化相同函数的其他目标文件之间的冲突?。是否有一些神秘的 C++ 命名空间 Juju 可以防止方法的单独对象实例相互冲突?

最佳答案

7.1.2 Function specifiers

A function declaration (8.3.5, 9.3, 11.4) with an inline specifier declares an inline function. The inline specifier indicates to the implementation that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism. An implementation is not required to perform this inline substitution at the point of call; however, even if this inline substitution is omitted, the other rules for inline functions defined by 7.1.2 shall still be respected.

因此,编译器不需要实际“内联”任何函数。

但是,标准还说,

An inline function with external linkage shall have the same address in all translation units.

成员函数通常具有外部链接(一个异常(exception)是当成员函数属于“本地”类时),因此在采用函数地址的情况下,内联函数必须具有唯一地址。在这种情况下,编译器将安排链接器丢弃除一个函数的非内联拷贝实例之外的所有实例,并将对函数的所有地址引用修复为保留的地址引用。

关于c++ - header 中定义的 C++ 类方法是否始终内联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8392885/

相关文章:

PHP curl 头

c++ - C++ 静态类 : undefined symbols 的 Clang 链接错误

C++ 链接失败-ld : cannot find [makefile] [gcc/cygwin]

asp.net - X-Frame-Options 允许来自多个域

c++ - Visual Studio 在编译 32 位时尝试使用 64 位 C 运行时库

c++ - 错误 LNK2019 : unresolved external symbol _Direct3DCreate9Ex@8 referenced in function "protected: XYX()"

c++ - 拒绝包含某些公共(public)静态数据成员的类型

c++ - Visual Studio 2015 在 constexpr 中使用 lambda

c++ - 发送USR2信号后忽略信号处理程序

c - 警告...已定义但未使用 - 我真的需要 .c 文件吗?