C Design Patterns – Separating Code into Smaller Files

cdata structuresdesigndesign-patternsglobals

I am in the process of cleaning up my code and making it easier to maintain. I am doing this by turning my 5000+ line file into separate smaller files.

I have successfully created separate source and header files for obvious things like utilities and other components that are not tightly integrated with the application.

I am now thinking it would be good to break up the rest of my application into smaller files also. But the issue mostly concerning me is that everything that is left uses a bunch of Structs that are Globally declared.

So this is the choice moving forward (happy to hear other suggestions also):

1) I could leave everything in the same file and that way I could just define all functions as static (which has its benefits, and is often recommended). It is then a simple choice to leave the Globals at the top of this large source file.

OR

2) I could separate into smaller files. It is relatively simple to work out which parts should go into which new files. It is also not too difficult to work out the structural hierarchy (which parts call which parts). But I am uncertain on how best to deal with all these Globals. Where should they be placed, since every function uses them in some way?

NOTE: I am aware that the use of Globals should be avoided. However this is an embedded device with limited memory. Globals are the best way to reduce memory usage, and the more memory I save, the more I can perform a certain task.

Best Answer

I would recommend typedef-ing all the structs, and putting those declarations in a separate include file. Then define all your actual instances of the structs in whatever your "main" file ends up being. Then, simply include the header and declare the needed instances extern in the other files. The linker will take care of matching up all the references, it shouldn't be any problem at all.

Related Topic