2

Consider the following code:

In header.h

#pragma once

class someClass
{
public:
    void foo();
};

In header.cpp

#include "header.h"

inline void someClass::foo(){}

In main.cpp

#include <iostream>
#include "header.h"
using namespace std;

int main()
{
    someClass obj;
    obj.foo();
}

Here I get a link error because foo function is defined as inline in header.cpp, if I remove the 'inline' keyword, the compile and run will proceed without errors.

Please tell me why I get link error on this 'inline' function?

Eduard Rostomyan
  • 7,050
  • 2
  • 37
  • 76
  • possible duplicate of [Inline functions in C++](http://stackoverflow.com/questions/2501776/inline-functions-in-c) BTW: Adds more detail than the current answer. – Deduplicator Apr 20 '14 at 17:12

1 Answers1

5

The way you wrote it, inline applies to the current file scope. When an inline function is in a header, that header is included in a cpp file, and then the function is inlined where it is used in that file's scope, so there is no problem. In this case, your function is available as inline only where it is defined, and no other cpp file sees it, except as a regular member declaration in its class, hence the link error.

If you want it to be inline, add the code and the inline keyword in the header.

DNT
  • 2,356
  • 14
  • 16
  • 1
    Btw, no need to use inline keyword in the header. In this case methods are inlined by default – grisha Apr 20 '14 at 17:30
  • 1
    Yes, this is true, as well as the fact that inline is a hint to the compiler, it does not guarantee that the function call will be replaced by the function's code at the places where it is called. – DNT Apr 20 '14 at 17:32