Sign in to follow this  

Linking errors when using inline methods

This topic is 4826 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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 this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites

This topic is 4826 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this