# Linking errors when using inline methods

## Recommended Posts

ZeroEffect    136
How can I set up inline methods outside of the header file in C++. If I have the following method declared in a class: void SetDistance( float distance ); How can I implement this as "inline" in the .cpp file. Whenever I try to use: inline void <classname>::SetDistance( float distance ) { m_Distance = distance; } I get a linkage error. If I implement the above in the header file, everything links fine. Where am I going wrong? Thanks, Chris Z.

##### Share on other sites
Evil Steve    2017
Thats the way it has to be done - in the header. Its because when you declare something as inline, the compiler needs to be able to copy the code to compile it in the place of the function call (well, its a bit more complicated than that, but thats the basic idea). If you put the code in the cpp file, then when the compiler comes to compile a different cpp file, it can't find the code because it only deals with one source file at a time.

So, you have to either put the code in the header, or use another file (I use "*.inl"), and #include it at the end of the header. That way keeps your header neat, but allows the compiler to find the code (because it gets #included).

E.g:
// Math.h:inline float Sin();inline float Cos();// etc#include "Math.inl"//== End of File ========================// Math.inl:inline float Sin(){   // Implementation}inline float Cos(){   // Implementation}//== End of File ========================

##### Share on other sites
izzo    437

http://www.parashift.com/c++-faq-lite/inline-functions.html

The C++ FAQ is a great resource, btw :-)

cheers
sam

## Create an account or sign in to comment

You need to be a member in order to leave a comment

## Create an account

Sign up for a new account in our community. It's easy!

Register a new account