简体   繁体   English

C++ 内联类方法导致未定义的引用

[英]C++ inlining class methods causes undefined reference

I'm getting a compiler error when I try to inline a method of one of my classes.当我尝试内联我的一个类的方法时出现编译器错误。 It works when I take away the "inline" keyword.当我去掉“inline”关键字时它会起作用。

Here's a simplified example:这是一个简化的示例:

main.cpp:主.cpp:

#include "my_class.h"

int main() {
  MyClass c;
  c.TestMethod();

  return 0;
}

my_class.h: my_class.h:

class MyClass {
 public:
  void TestMethod();
};

my_class.cpp: my_class.cpp:

#include "my_class.h"

inline void MyClass::TestMethod() {
}

I try compiling with:我尝试编译:

g++ main.cpp my_class.cpp

I get the error:我收到错误:

main.cpp:(.text+0xd): undefined reference to `MyClass::TestMethod()'

Everything is fine if I take away the "inline".如果我去掉“内联”,一切都很好。 What's causing this problem?是什么导致了这个问题? (and how should I inline class methods? Is it possible?) (我应该如何内联类方法?这可能吗?)

Thanks.谢谢。

The body of an inline function needs to be in the header so that the compiler can actually substitute it wherever required.内联函数的主体需要位于头文件中,以便编译器可以在任何需要的地方实际替换它。 See this: How do you tell the compiler to make a member function inline?看到这个: 你如何告诉编译器使成员函数内联?

7.1.2/4 of the Standard:标准的7.1.2/4:

An inline function shall be defined in every translation unit in which it is used...内联函数应在使用它的每个翻译单元中定义......

You use TestMethod in main.cpp, but it's not defined there.您在 main.cpp 中使用了 TestMethod,但它没有在那里定义。

... If a function with external linkage is declared inline in one translation unit, it shall be declared inline in all translation units in which it appears; ... 如果具有外部链接的函数在一个翻译单元中声明为内联,则应在其出现的所有翻译单元中声明为内联; no diagnostic is required.不需要诊断。

You define (and hence also declare) TestMethod inline in my_class.cpp, but not in main.cpp.您在 my_class.cpp 中定义(并因此也声明)TestMethod 内联,但不在 main.cpp 中。

The fix in this case is to move the function definition to the header file, either like this:这种情况下的解决方法是将函数定义移动到头文件中,如下所示:

class MyClass {
 public:
  void TestMethod() {}
};

or like this:或者像这样:

class MyClass {
 public:
  inline void TestMethod();
};

inline void MyClass::TestMethod() {}

You've defined it as not inlined in the header file, while in the cpp file you're trying to define it as inline.您已在头文件中将其定义为未内联,而在 cpp 文件中您试图将其定义为内联。 That's a conflicted definition and it won't be able to find one from the other.这是一个相互矛盾的定义,它无法从另一个中找到一个。 Your header is where you really place the inline keyword.您的标题是您真正放置 inline 关键字的地方。

However, I'd remove the inline keyword as it's really more of a suggestion to the compiler anyways.但是,我会删除 inline 关键字,因为它实际上更像是对编译器的建议。 You really only need it when there's a free-floating function in the header and you don't want multiple definitions popping up in your code base.只有当标题中有一个自由浮动的函数并且您不希望在您的代码库中弹出多个定义时,您才真正需要它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM