inline function linker error

可紊 提交于 2019-11-28 05:50:40

You need to put function definition into the header then. The simplest way to hint the compiler to inline is to include method body in the class declaration like:


class NeedleUSsim
{
  // ...
  int GetTplLSize() const { return sampleDim[1]; }
  // ...
};

or, if you insist on separate declaration and definition:


class NeedleUSsim
{
  // ...
  int GetTplLSize() const;
  // ...
};

inline int NeedleUSsim::GetTplLSize() const
{ return sampleDim[1]; }

The definition has to be visible in each translation unit that uses that method.

young

from C++ FAQ Lite

If you put the inline function's definition into a .cpp file, and if it is called from some other .cpp file, you'll get an "unresolved external" error from the linker.

How do you tell the compiler to make a member function inline?

As others have already pointed out, you need to move the definition of the inlined function to the header file, like so:

class NeedleUSsim
{
  // ...
  inline int GetTplLSize() { return sampleDim[1]; }
  // ...
};

The reason for this is that the compiler needs to know what code to inline when it sees a call to the inlined function. If you leave the definition of the function in the .cpp file for the NeedleUSsim class, the code that the compiler generates for it becomes trapped in the the NeedleUSsim object file. As the compiler only reads source code—it never peeks into another class's object file—it simply has no way to know with what code to replace a call when it's compiling another .cpp file.

If you have an inline function you should put the definition in the header file.

grepsedawk

See the Inline Guard Macro idiom. This will at least allow you to separate, albeit slightly, the code from the declaration. It also allows you to toggle inlining of functions via a define.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!