linking/including

linking/including

Post by Steven Dae » Fri, 14 Jan 2005 05:58:21


Hi all,

Help a fairly clueless guy: Let's say I add source1.cpp to a project. It
refers to functionX defined in source2.cpp. Now, if I put include
"source2.cpp" at the top of source1.cpp, it works ok. If I add
source2.cpp to the project, it tells me that functionX is undefined.

Perhaps I just don't understand linking. Could someone explain this to
me?

sp
 
 
 

linking/including

Post by Paul » Fri, 14 Jan 2005 06:42:51


When you #include "source2.cpp", you effectively add the entire file to the
beginning of source1.cpp. Everything in source2.cpp is compiled before
everything in source1.cpp, and it works.

When you add source2.cpp to the project, it is compiled separately and
linked in; however, source1.cpp no longer sees it (the error you're seeing
means that the compiler doesn't know what functionX is, and can't generate
code to call it: the linker isn't involved at this point, and the compiler
only sees what you tell it to.)


If you #include source2.cpp everywhere it's referenced, it willl work but
source2.cpp will have to be compiled every time a file that #include's it is
Any changes to source2.cpp would force every file that #included it to be
rebuilt as well
Your binary might not get bigger (modern linkers are pretty good at spotting
redundant code and removing it) but your build times will increase.


You should:
Add source2.cpp to your project: that way it gets compiled once
#include source2.h (which should at least include a declaration of
functionX) to every file that needs it. That way the compiler knows
functionX is defined and the linker will look for and reference it properly.
Now you can change source2.cpp without forcing anything else to recompile
(as long as the declarations in source2.h don't change.)

Another way is to declare functionX extern in source1.cpp. This simply tells
the compiler that the function is defined and prevents an error, and the
linker takes care of locating the right code in source2.cpp. This isn't
generally a good idea for several reasons, notably that you will have
trouble if functionX's declaration ever changes (you'll have to hunt down
every single extern declaration and fix it, instead of fixing it once in
source2.h.)


This is just the way C works: a separate header that lets files refer to
each other (a type of forward declaration.) Pascal and other
module-structured languages handle this by effectively generating their own
headers from the source code and #including it automatically. there have
been several attempts to do this with C-style languages (google MakeHeaders,
for example, but it's pretty limited w/ C++.)

 
 
 

linking/including

Post by Steven Dae » Fri, 14 Jan 2005 07:17:40

In article <vRgFd.4749$ XXXX@XXXXX.COM >,





Oh, of course. That makes perfect sense. Many thanks.