Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can't define inline member function in another file?

Tags:

c++

inline

I have three files:

1. Joy.h

class Joy
{
public:
    void test();
};

2. Joy.cpp

#include "Joy.h"
inline void Joy::test() {}

3. main.cpp

#include "Joy.h"    
int main()
{
    Joy r;        
    r.test();        
    return 0;
}

I try to compile them using:

g++ cpp Joy.cpp

g++ say:

main.cpp:(.text+0x10): undefined reference to `Joy::test()'

Who can tell me why...

How to solve this problem if I don't want to define that test() function in the .h file and still want it to be an inline function?

like image 634
Yishu Fang Avatar asked Mar 10 '12 17:03

Yishu Fang


2 Answers

when you define an inline member function, you should prepend the member function's definition with the keyword inline, and you put the definition into a header file.

When you declare a function inline basically You are telling the compiler to (if possible)replace the code for calling the function with the contents of the function wherever the function is called. The idea is that the function body is is probably small and calling the function is more overhead than the body of the function itself.

To be able to do this the compiler needs to see the definition while compiling the code which calls the function this essentially means that the definition has to reside in the header because the code which calls the function only has access to the header file.

Good Read:
[9.7] How do you tell the compiler to make a member function inline?

like image 56
Alok Save Avatar answered Nov 30 '22 23:11

Alok Save


From the standard (N3242, 7.1.2.4):

An inline function shall be defined in every translation unit in which it is used and shall have exactly the same definition in every case.

Have a look here as well: How do you tell the compiler to make a member function inline?

like image 32
Bojan Komazec Avatar answered Dec 01 '22 00:12

Bojan Komazec