Split .cpp files without code changes

I have a .cpp that is getting quite large, and for easy management, I would like to split it into several files. However, there are many global variables, and I would like to avoid managing a bunch of extern declarations in different files. Is there a way for multiple .cpp files to act as a single file? In essence, I would like to split the code without recognition by the compiler of division.

+4
source share
3 answers

Of course, you can always simply # include various CPP files in one main file that the compiler sees. However, this is a very bad idea, and you will end up in headaches much worse than refactoring a file.

+5
source

Is there a way for multiple .cpp files to act as a single file?

Yes. This is the definition of #include . When you #include file, you create a text replacement for the included file instead of the #include directive. Thus, several included files act together to form one translation unit.

In your case, we interrupt the file for several bits. Do it for sure - do not add or diminish lines of text. Do not add title controls or anything else. You can split your files in almost any convenient place. Limitations: a break must not occur inside a comment or inside a line, and it must appear at the end of a logical line.

Name the newly created partial files according to some conventions. They are not fully formed translation units, so do not call them *.cpp . They are not proper header files, so do not name them *.h . Rather, they are partially complete translation units. Perhaps you could name them *.pcpp .

As for the base name, select the original file name with a serial number: MyProg01.pcpp , MyProg02.pcpp , etc.

Finally, replace the source file with a series of #include statements:

 #include "MyProg01.pcpp" #include "MyProg02.pcpp" #include "MyProg03.pcpp" 
+5
source

while you can declare the same set of globals in many cpp files, you will get a separate instance of each of them when the compiler compiles each file, which then will not be linked as they are combined.

The only answer is to put all your global variables in your own file and then cut and paste them into the header file containing extern declarations (this can be easily automated, but I find using the arrow keys to just insert the 'extern' in front of them quickly and just).

You can reorganize everything, but often it’s not worth the effort (unless you need to change something for other reasons).

You can try to split the files, and then use the compiler to tell you what global values ​​are needed for each new file, and re-enter only those that are directly in each file, keeping the true global variables separately.

If you do not want to do this, simply #include cpp files.

+1
source

Source: https://habr.com/ru/post/1415861/


All Articles