Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting .cpp files without code changes

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.

like image 209
Cannoliopsida Avatar asked Dec 16 '22 23:12

Cannoliopsida


2 Answers

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"
like image 145
Robᵩ Avatar answered Jan 10 '23 07:01

Robᵩ


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.

like image 21
harald Avatar answered Jan 10 '23 09:01

harald