Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top