Search code examples
javaccode-organizationmodularity

Transition from Java to C code organisation


When programming in Java, I obviously keep related code in classes, organizing a class structure, hierarchy etc to maximize code reuse.

Now I am starting to use C, and am a little confused as to the best way to organize C code in a modular manner. Obviously I am aware of headers and source files, but am somewhat at a loss when it comes to maximizing code reuse in C.

So, how do people organize their code in a language such as C which obviously is not supportive of OOP.


Solution

  • The two languages are different in that java is more modern and designed for OOP

    C is older, and is and is a proceedural language. Because the languages are different, the way we program is generally different and so is layout.

    C programs have headers (and function prototypes) in the .h and the functional code in the .c file.

    In terms of modularity, you can still follow similar patters to java in the way that you section off your code. The general rule of thumb is that one file should do one thing, i.e. string_parser.c should only deal with string parsing. list_sorter.c should deal with list sorting etc.

    In terms of code reuse - things like "utility" files are good so reusable useful code can go in the one C file and included where needed. You should never have to duplicate code in C, so if you find yourself copy/pasting functions put it in a centeralised file and include it in multiple places.

    Write generic functions! keep you functions simple and open so they are less specific, that way you can reuse your functions.

    My advise is to keep your Java code layout knowledge in mind, but also check a good C guide. http://www.doc.ic.ac.uk/lab/cplus/cstyle.html

    Generally good project design will help you work out the file layout / structure of the project.