I have a .cpp that's getting rather large, and for easy management I'd like to split it into a few files. However, there are numerous globals, and I'd like to avoid the upkeep of managing a bunch of extern declarations across different files. Is there a way to have multiple .cpp files act as a single file? In essence, I'd like a way to divide the code without the division being recognized by the compiler.
Is there a way to have multiple .cpp files act as a single file?
Yes. That is the definition of #include
. When you #include
a file, you make a textual substitution of the included file in place of the #include
directive. Thus, multiple included files act together to form one translation unit.
In your case, chop the file into several bits. Do this exactly -- do not add or detract any lines of text. Do not add header guards or anything else. You may break your files at almost any convenient location. The limitations are: the break must not occur inside a comment, nor inside a string, and it must occur at the end of a logical line.
Name the newly-created partial files according to some convention. They are not fully-formed translation units, so don't name them *.cpp
. They are not proper header files, so don't name them *.h
. Rather, they are partially-complete translation units. Perhaps you could name them *.pcpp
.
As for the basename, choose the original file name, with a sequentially-numbered suffix: MyProg01.pcpp
, MyProg02.pcpp
, etc.
Finally, replace your original file with a series of #include
statements:
#include "MyProg01.pcpp"
#include "MyProg02.pcpp"
#include "MyProg03.pcpp"
Of course, you can always just #include the various CPP-files into one master file which is the one that the compiler sees. It's a very bad idea though, and you will eventually get into headaches far worse than refactoring the file properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With