Undefined reference when inline specifier used wit

2019-02-28 08:39发布

I have some member functions in a class. When I use the inline specifier, the compiler complains of undefined reference.

I have tried:

Using 'inline' to precede the function definition in the class header file only.

Using 'inline' to precede the function declaration in the class .cpp (where the member functions are specified) file only.

Doing both of the above at the same time.

Obviously, one of these ways is the correct thing to do, and the others are not correct. However trying each option did not get me a program which compiled.

Here is what I am trying to do:

.hpp file:

class A{
    void func();
}

.cpp file:

... include ...

inline void A::func()
{ 
    ...
}

Or maybe 'inline' goes elsewhere. I have tried all possible combinations I could think of, as I explained above. (Now watch someone tell me I need it AFTER the function name and arguments, like the keyword 'const'.)

Anyone any ideas on what I am doing wrong? I tried googling what the correct answer might be, but no luck. Are 'inline' functions inside a class even a thing?

2条回答
相关推荐>>
2楼-- · 2019-02-28 09:35

Inline functions have to be defined in header files. The definition (the body) of the function has to be visible in all translation units that attempt to use that function. You can define it directly inside the class. Or you can define it as in your code, i.e. outside of the class. But it has to be in header file, not in .cpp file.

Attempting to define an inline function in .cpp file will make it usable in that .cpp file only. Trying to use it in other .cpp files will lead to linker errors (i.e. "undefined reference" errors).

查看更多
Summer. ? 凉城
3楼-- · 2019-02-28 09:35

Putting inline anything inside the CPP file can only possibly inline the function inside that file. If you want to encourage the compiler to inline the function, you need to forget about the CPP file. Instead, do this in the hpp file:

class A{
  inline void func();
};

void A::func() {...}

NB a few points:

  1. Putting inline doesn't mean your function will be inlined. It's a hint to the compiler.
  2. You need optimization (-O3 in gcc) to even have a chance at it being inlined
  3. If you define the function inside the class, it implicitly has the inline keyword on:

    class A{
      inline void func() {
        ...
      }
    };
    

    is the same as the above where it was declared inline in the class and the definition was outside.

There are ways to force GCC to inline your code using function attributes, but I will not describe them because it is rarely a good idea to use them. GCC should do the "best" thing regarding inlining for each function. Forcing it to do something else will almost always result in worse performance.

查看更多
登录 后发表回答