Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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"

whilst you can declare the same set of globals in many cpp files, you will get a separate instance of each as the compiler compiles each file, which will then fail to link as they are combined.

The only answer is to put all your globals in their own file, then cut&paste them into a header file that contains extern declarations (this can easily be automated, but I find using the arrow keys to just paste 'extern' in front of them is quick and simple).

You could refactor everything, but often its not worth the effort (except when you need to change something for other reasons).

You could try splitting the files, and then using the compiler to tell you which globals are needed by each new file, and re-introducing just those directly into each file, keeping the true globals separately.

If you don't want to do this, just #include the cpp files.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top