Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you carry out modularized development in c/c++?

Tags:

c++

modularity

I can deal with only the easiest case, when there are only 2 modules A and B

A is dependant on B, so I build B as a library and include B's header file in A, also link to B library when building A.

This won't work when A and B are inter-dependant, and even worse when the number of modules grow ..

So what's the general way to carry out modularized development in c/c++?

UPDATE

Sorry, seems my title is inacurate, the rephrased version is: how can I divide a module into many .h and .cpp files(not a single one)?

like image 773
Alan Avatar asked Aug 23 '10 14:08

Alan


2 Answers

If A and B are inter-dependant, you can't deploy any of them in isolation. Therefore you practically have a single module, not two. (You can refactor your modules to extract the common stuff into a third module C though, thus making both A and B depend on C but not on each other.)

A well designed project shall not contain cyclical module dependencies. This guarantees that there is always a sane build order between its modules.

Update

how can I divide a module into many .h and .cpp files(not a single one)?

The basic principle is pretty similar to that of the module level: avoid cyclic dependencies and duplicate definitions. @Felix already mentioned the essential tools for this: forward declarations and include guards. I can also second @kotlinski's recommendation of the Larman book for a deeper understanding of the topic.

Learning good design takes practice, so don't give up if your first approach doesn't look perfect :-) In C++, one particular pain is excessive recompilation after changes. To minimize this, strive to ensure that the things (classes, headers) you depend on the most are the ones which change the least frequently. I.e. depend on interfaces (abstract classes), not concrete implementations.

Also, strive to keep a healthy relationship between the logical partitioning (classes/components) and the physical partitioning (header/cpp files). The typical way is to put every class definition into a separate header file, and its implementation (if applicable) to a separate cpp file. However, you may prefer defining tightly coupled classes (components) in a single header, to emphasize their logical relationship.

like image 165
Péter Török Avatar answered Sep 28 '22 03:09

Péter Török


Generally speaking, having two interdependent modules is a design smell. You can either

1) merge the modules into a new one C, or

2) extract a common subset into I, making A and B depend on I but not each other.

update

Use forward declarations and #pragma once or #include/#ifndef protection:

When can I use a forward declaration?

Should I use #include in headers?

like image 23
Felix Ungman Avatar answered Sep 28 '22 03:09

Felix Ungman