C++: Link errors caused by inline functions

When we want a C++ function to be inlined, that is, to have its calls replaced by its code in order to save the calling overhead, one way to achieve is to declare and define it in the .h file, and add the inline keyword. However, that's just a hint to the compiler, he'll decide whether to inline it or not.

However, if we are keen on separating declaration and definition, we should declare the function in the .h file, without the inline keyword, and define it in the .cpp withthe inline keyword.

So far, so good. But there's a catch: If we go for the "cpp inline" approach, and the function is called from another compilation unit (.cpp), we'll get a linking error saying something like the function definition cannot be found.

In this case, we have two choices:

  1. Place the function definition in the .h file, but outside of the class declaration. This avoids cluttering its interface. This way:
    class A{
    public:
       inline void foo();
    };
     
    void A::foo(){
       //do stuff
    }
  2. Put the inline function definitions inside another file, say a .inl, and #include it at the end of the .h file.

Comments

Popular posts from this blog

VB.NET: Raise base class events from a derived class

Apache Kafka - I - High level architecture and concepts

C++/CLI: Convert a String to BSTR or some other nasty stuff