Huang-zh
Huang-zh

Reputation: 147

Why putting inline function def in other header file which include the header file where the inline function declaration in is a link error?

I have two headers.

// header1.h
class A
{
public:
    void f();
};

// header2.h
#include "header1.h"
inline void A::f()
{
    std::cout << "Yahoo.";
}

// test1.cpp
#include "header1.h"
int main() { A a; a.f(); return 0; }

// test2.cpp
#include "header2.h"
void ff() { /* do nothing */ }

I got a link error on MSVC 2013. I only got one translation unit, so I think that maybe "ODR" is not the reason?

Now I have test2.cpp to include header2.h. So I think that linker can find header2.h now. But still link error, why?

Upvotes: 0

Views: 78

Answers (2)

wolfPack88
wolfPack88

Reputation: 4203

Your compiler doesn't know where to find A::f() because you've never told it where to look. You need to #include "header2.h" in test.cpp. Either that, or move the definition of A::f() into header1.h.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409196

That's not how you do it with inline function. In the test.cpp file, how would the compiler even know that the function A::f is marked inline?

If you want an inline member function, you have to define it in the same header file, or include the header file where it's defined.

So solution one: #include "header2.h" instead of "header1.h".

Solution two: Define the function inline inside the class:

class A
{
public:
    void f() { ... }
};

Solution three: Define the function after the class but in the same header file:

class A { ... };

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

Upvotes: 3

Related Questions