Sign in to follow this  

Separating definition and implementation.

This topic is 4178 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

I've read here and there on this site that I should put the definitions of stuff in a header file and the implementations in a source file of the same name. How do I make the header recognize its source file? Should I just put a line at the bottom: #include "headerName.cpp" ?

Share this post


Link to post
Share on other sites
No.

You would compile each .cpp file seperately into a .obj file, then link your various .obj files into an exe.

The purpose of a .h file is to be included in the top of more than one .cpp file so that one .cpp file has access to the definitions that are implemented in another.

x.h

class point
{
public:
point(int x=0,int y=0);

int X,Y;
};



x.cpp

#include "x.h"

point::point(int x,int y) : X(x),Y(y)
{
}



main.cpp

#include "x.h"

int main()
{
point p(10,20);

return 0;
}



main.cpp sees only that a constructor taking two ints exists for the point class. It doesn't see the implementation when it is compiled into an object file so the relevant call is omitted from its object file and marked as unresolved.

When main.obj is linked to x.obj, the linker identifies the correct location to call the function and resolves this and any other unresolved entity before producing a final executable.

HTH Paul

Share this post


Link to post
Share on other sites

This topic is 4178 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