Wednesday 16 November 2011

Should my program be written in one source file or several source files? in C programming

Should my program be written in one source file or several source files?

If your program is extremely small and focused, it is perfectly OK to contain all the source code within one .c file. If, however, you find yourself creating a lot of functions (especially general-purpose functions), you will want to split your program into separate source files (also known as modules).

The process of splitting your source code into several source files is known as modular programming. Modular programming techniques advocate the use of several different focused modules working together to makeup a complete program. For instance, if your program has several utility functions, screen functions, and database functions, you might want to separate the functions into three source files that make up the utility module, screen module, and database module.

By putting your functions in separate files, you can easily reuse your general-purpose functions in other
programs. If you have several functions that can be used by other programmers, you might want to create a function library that can be shared with others (see FAQ XVIII.9).

You can never have “too many” modules—you can create as many for your program as you see fit. A good rule of thumb is to keep your modules focused. Include only functions that are logically related to the same subject in the same source file. If you find yourself writing several nonrelated functions and putting them in the same file, you might want to pause to look at your program’s source code structure and try to create a logical breakdown of modules. For example, if you are creating a contact management database, you might want to have a structure like this:

Module Name                 Contains
-------------------------------------------------------------------------------------------------------------------
Main.c                           The main() function
Screen.c                         Screen management functions
Menus.c                         Menu management functions
Database.c                      Database management functions
Utility.c                          General-purpose utility functions
Contact.c                        Functions for handling contacts
Import.c                         Record import functions
Export.c                         Record export functions
Help.c                            On-line help support functions
------------------------------------------------------------------------------------------------------------------

Cross Reference:

XVIII.10: My program has several files in it. How do I keep them all straight?


No comments:

Post a Comment