Hi all,

I'm sure this is a trivial question for the veterans (and the newbs maybe as well). But I just can't find a straight answer to it. So here it goes:

I have my main.cpp file, and 2 more files, custom.h and custom.cpp. Obviously, custom.h would contain declarations, prototype...etc, and custom.cpp would contain the actual code. So now I want to make things work together.

Now I'm sure (but if I'm wrong, please correct me) that the *.h file is included in the *.cpp file. So we have:

// custom.h
/* Declarations, prototypes...etc */
// custom.cpp
include "custom.h"
/* Actual code */

Now, in all the examples I could find on the net, only the *.h file is included in main.cpp

// main.cpp
include "custom.h"
/* main function */

Now my question is: Is this correct? If so, then how does the linker figure out that it needs to link the file custom.cpp into our party? Is it just because it shares the name with the *.h file? Or is there something beyond that (which I have no idea about)?

Note: I don't have a running compiler at the moment, so it's gonna be some time before I can try anything.

Thanks all,
Khaled

When main.cpp is compiled the compiler generated main.obj (or main.o depending on the os). When custom.cpp is compiled the compiler generated custom.obj. The linker uses both main.obj and custom.obj, as well as other libraries, to create the executable program.

How does the linker know how to do that? It depends on the compiler and IDE you are using. With both Code::Blocks and VC++ 2010 you have to start out by creating a project then add both main.cpp and custom.cpp to that project. With olther command-line driven compilers you might have to create makefiles, which is a text file that tells the compiler and linker what to do.

No point in being any more specific until you tell us what compiler and operating system you are using.

Thanks for the quick (yet informative) reply.

So from your post, I can safely assume that:
1- Only including *.h in main.cpp is correct.
2- The linker doesn't (normally) figure it out on its own (or by filename), but there's something hidden being done by the IDE.

I'm on a linux machine, and I remember seeing *.o files (so I guess that's the object file you mentioned). Using Eclipse and I think the compiler is "g++"

1) Yes that is correct

2) Its not really hidden if you look around Eclipse options -- I don't use Eclipse so I do know. Eclipse probably generates a makefile that g++ uses.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.