Search code examples
c++gitcode-organizationpragma

Elegant way of handling similar code


I have a software project that is working just fine. Now, this project has to be adjusted to model a new, but related system. What strategies are there to keep these two codes well organized? They will have a codebase that is about 90% the same, but there are many functions which need slight adjustments.

I have thought of the following:

  1. Different branches in the git-repository: perfect control of the two projects, but common changes have to be made in each of the branches separately.
  2. Modelling different program modes by C++ pragmas (#ifdef Project1 ...): this keeps the changes local, but makes the code difficult to read.

I am not too satisfied by these solutions. Is there a better approach?


Solution

  • We have same problem and here is how we solve it:

    • We have only one branch on our git repo
    • Beside common files, we have different files according configuration: access_for_config1.cpp, access_for_config2.cpp, ...
    • We use design pattern like factory to abstract specific part for common part
    • For small very specific parts on common files, we have a #ifdef section according configuration
    • We have different rules in our makefile according each configuration: for a configuration, we compile common file + specific file and set correct flag. Also, using eclipse at office, we also define different build configuration, to allow correct highlighting.

    Advantage of this approach is to keep common part always synchronous, and we isolate correctly each specific parts.

    But, you have to be careful with not so far piece of code from each configuration. For example, with similar (but not same) code in different specific files, possible bug can be corrected in only one configuration. It can be reduce by defining some piece of code as common template or by re-thinking design to put some part in common

    Hope it's answer will help you