Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to organize my c code

Tags:

c

I have large main file contains about 7,000 lines of C code. If I want to make this code modular and separate the code from this file. what is the main criteria for separating the functions out of the file and functions that should stay in the file.

like image 759
brett Avatar asked Sep 05 '10 04:09

brett


People also ask

What are the two main ways a file can be organized in C?

Reading from file (fscanf or fgets) Writing to a file (fprintf or fputs)

How do you organize your programs?

The best way to organize your engagement program is with folders. Make a folder for each stream and then put the emails or programs into that folder. Include an archive folder in each stream when content gets stale and you want to remove it.

How do I create a .C file?

To write a C code file in Notepad, type your C code into a blank page in the text editor, and then save the file with a ". c" file extension if the file consists of a C code page, or the ". h" file extension if the file consists of header code.


3 Answers

  • Follow earlier suggestions.
  • Eliminate any duplicate or almost duplicate code by creating functions.
  • Organize by functionality and dependency. Modules should have as little inter-dependency as possible.
  • Follow SOLID Principles and other design patterns and practices (all of which can be implemented in some degree in C).

I like to use a top-down decomposition of the code. For example:

main()
{
    Initialize();
    Introduce();
    while (some_condition)
    {
        DoSomething();
        DoSomethingElse();
    }
    SayGoodbye();
    Shutdown();
}

The main() should be short and to the point and give you a quick overview of what the program does from a high-level. Each of these functions can be broken down in a similar way. This should continue until the lowest level functions have a single, focused purpose (logical modularity). These functions can be put into additional .c/.h files to have physical modularity.

Good luck!

like image 99
Edward Leno Avatar answered Oct 03 '22 07:10

Edward Leno


Break up by functionality/responsibility.

For example, place all string handling in one module/file, place file handling in another.

like image 42
Mitch Wheat Avatar answered Oct 03 '22 06:10

Mitch Wheat


It is a simple measure: the fewer declarations you have in the .h file, the more modular it is. Grouping by functionality is important. Having extern declarations is very bad, give those an extra 'penalty'.

like image 39
Hans Passant Avatar answered Oct 03 '22 07:10

Hans Passant