문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top