Distribution of .cpp and .h files

This forum can be used to talk about general design strategies, new ideas and questions in general related to wxWidgets. If you feel your questions doesn't fit anywhere, put it here.
Post Reply
Thunderchook
Earned a small fee
Earned a small fee
Posts: 17
Joined: Wed Feb 01, 2017 9:59 am

Distribution of .cpp and .h files

Post by Thunderchook » Sun Feb 19, 2017 12:22 pm

Hi all,

I've been working through the zetcode.com 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.

User avatar
eranon
Can't get richer than this
Can't get richer than this
Posts: 867
Joined: Sun May 13, 2012 11:42 pm
Location: France
Contact:

Re: Distribution of .cpp and .h files

Post by eranon » Tue Feb 21, 2017 8:11 pm

Hello,

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).
[Ind. dev. - wxWidgets 3.0/3.1 under "Win 7 64-bit, TDM64-GCC" + "OS X 10.9, LLVM Clang"]

Thunderchook
Earned a small fee
Earned a small fee
Posts: 17
Joined: Wed Feb 01, 2017 9:59 am

Re: Distribution of .cpp and .h files

Post by Thunderchook » Thu Feb 23, 2017 11:45 am

Okay.
Many thanks for that explanation.

T.

Post Reply