Reputation: 1531
I am having trouble inlining member functions. My code is as follows:
Main.cpp
#include "Foo.h"
int _tmain(int argc, _TCHAR* argv[])
{
Foo foo;
int a = foo.myInlinedFunc(2);
}
Foo.h
class Foo
{
public:
Foo(void);
~Foo(void);
inline int myInlinedFunc(int value);
};
Foo.cpp
#include "Foo.h"
Foo::Foo(void)
{
}
Foo::~Foo(void)
{
}
int Foo::myInlinedFunc(int value)
{
return value * value;
}
I get the following error:
Tester.obj : error LNK2019: unresolved external symbol "public: int __thiscall Foo::myInlinedFunc(int)" (?myInlinedFunc@Foo@@QAEHH@Z) referenced in function _wmain 1>E:\Debug\Tester.exe : fatal error LNK1120: 1 unresolved externals
I have searched google for answers, but the only answers that show up, tells me that I should put the inline keyword in the header-file where it already is.
Upvotes: 1
Views: 242
Reputation: 1
You can do 1 of 2 ways
Put definition of the inline function (in your example is myInlinedFunc) in the header file
If you want to put definition of the function in another file, let add the following line at the end of the header file
#include "Foo.cpp"
And in Foo.cpp, add this line at the top of file
#include "Foo.h"
Upvotes: -1
Reputation: 26164
The source of functions' definitions need to be available for the compiler if you want to have them inlined. You can keep it in the header, or have it in a .cpp file which you include in the header.
For example, this would be Foo.h
#ifndef Foo_h
#define Foo_h
class Foo
{
public:
Foo(void);
~Foo(void);
inline int myInlinedFunc(int value);
};
#include "Foo.cpp"
#endif Foo_h
You can keep definition of the function in Foo.cpp
inline int Foo::myInlinedFunc(int value)
{
return value * value;
}
To use the class just include Foo.h where you need it. You don't need to compile Foo.cpp separatly.
Upvotes: 0
Reputation: 612794
You need to put the function body, i.e. the definition, in the header file.
Your header needs to read like this:
Foo.h
class Foo
{
public:
Foo(void);
~Foo(void);
inline int myInlinedFunc(int value)
{
return value * value;
}
};
And naturally you also have to remove the definition of myInlinedFunc
from Foo.cpp
.
Or, if you prefer, you can write your header code like this:
Foo.h
class Foo
{
public:
Foo(void);
~Foo(void);
int myInlinedFunc(int value);
};
inline int Foo::myInlinedFunc(int value)
{
return value * value;
}
But the bottom line is that if you need your function inlined, and available to other translation units, its definition must be placed in the header file.
The C++ FAQ explains this and even predicts your unresolved external error.
Upvotes: 10
Reputation: 8028
If you want to share the inlined function (be usable outside the class it is in), the function must must go into the header. It doesn't need to go into top part of the header. Put it outside of the class declaration but in the same *.h file.
Upvotes: 0