Page 1 of 1

Distribution of .cpp and .h files

Posted: Sun Feb 19, 2017 12:22 pm
by Thunderchook
Hi all,

I've been working through the tutorials and am finding them most helpful.
A once blurry picture is starting the form a much clearer picture in my mind, such that I may be able to start writing my own GUI apps in the semi-near future.

One question - I notice that these tutorials break a nominal-length program into 4 or more individual files such as main.h, main.cpp, subject.h, subject.cpp, anotherone.h, anotherone.cpp.
Out of curiosity, I piled all this code into one, long file and it compiled and it ran just fine.

I've noticed that these header files don't even follow the same exact format as C++ header files (e.g. beginning with #ifndef MY_FUNCTION_H
#define MY_FUNCTION_H etc)

So, is there a reason to cut the code up into several files or is this just a preference of the guy who wrote the tutorial?

Many thanks.

Re: Distribution of .cpp and .h files

Posted: Tue Feb 21, 2017 8:11 pm
by eranon

A single file project is OK for small things, but generates unecessary compilation and quickly becomes difficult to browse when the project growths. So, the modularity allows to recompile what necessary only (knowing your compiler is able to work incrementally of course), helps you to stay organized (say one class -- and its underlying assets -- per .cpp/.h pair and you immediatly see what does what)... Also, if you have to re-use (since it's the initial goal of an object oriented language like C++) a class, it's far easy if you simply have to share (or copy) a pair of "self-governing" files.

It's also a big comfort when you work in team at time everyone has to commit toward a versions management system (Subversion, Git, etc)...

About what you red at beginning and end of the header files, it's what we call a guards. They prevent any multi-inclusion. For example, when an header (aaa.h) includes another header (bbb.h), if an implemtation file (zzz.cpp) includes both aaa.h and bbb.h, the bbb.h one will be skipped (because already included through aaa.h).

Re: Distribution of .cpp and .h files

Posted: Thu Feb 23, 2017 11:45 am
by Thunderchook
Many thanks for that explanation.