How to distribute code in multiple .cpp files for readability

I have a .h file with many different functions related to the same function in the program. There are constants and constant arrays, they do go in .h file or in .cpp file? If they go into .cpp are they not mentioned at all in .h file?

Also, if I define all functions in a single .cpp file, it shall become quite long (from human perspective). I would rather that the functions be distributed across multiple .cpp files. In some cases one function may call other function within this huge .cpp as well.

Is it possible to distribute the code across multiple .cpp files?
How are they do to be named? Is this a good practice?
styles affect this somewhat. I code to the least exposure principle. So if you have a constant that is only used inside a cpp file for a couple of functions, but isnt needed by other code anywhere, that goes in the cpp file. If its used by other code, like PI or something, it goes in a header file. If its only used inside a class, it goes in the class as a const member. Constants that are used by other code (the ones in the H file) should be in a namespace.

I make 1 cpp and 1 h file for all classes.
I also group like stand-alone functions in one cpp/h file pair. If these become too large, you can make a finer grained grouping to determine what is alike.

It is almost always possible to distribute code across files, the exception is that some template class code can be tricky or impossible to break apart.

naming the files is up to your conventions, but figure out a pattern and stick to it. It should describe what the file has inside in a word or two.

You don't mention anything about classes. As jonin mentioned, the usual convention is one .cpp and one .h file for each class. If you're not using classes, that's suspect, although there can be legitimate programs that don't use classes.

Do your functions fall into logical groups? If so, that would be the way to separate them into separate .cpp files. I would make a .h file for each .cpp file which contains the declarations for the functions in the corresponding .cpp file.



Topic archived. No new replies allowed.