Pseudo Associative

Random thoughts on software development

6 notes

How a C program naturally scales better than a C++ program

I am currently in the process of rewriting a simple 2D game engine from C++ to C. Having always been a C++ programmer I am used to think in terms of classes. So I have done this in C as well. So here is an excerpt from how I originally wrote my header file for dealing with 2D vectors.

typedef struct _Vec
  real x, y;
} Vec;

//- Constructors
Vec vec(real x, real y);

//- Calculations
Vec  vecAdd(Vec u, Vec v);
Vec  vecSub(Vec u, Vec v);
Vec  vecMul(Vec v, real factor);

This is pretty much how a C++ guy would do it. Data definition and associated operations are put in the same place. Most other “classes” which takes 2D vectors as input would include this header file. However it gradually dawned upon me that this was completely unnecessary. Those other header files only needed to know the memory layout of a 2D vector. They didn’t need to know the associated functions. So I moved the struct definition out of the file and only included that in other header files which defined functions accepting 2D vectors. An example is my 2D matrix class. The excerpt below shows how it was originally. The header file included all the 2D vector functions (as a C++ class would).

#include "geometry/vec.h"

Mat matIdentity();
Mat matTranslate(Vec v);
Mat matMul(Mat m, Mat n);
Vec matMulVec(Mat m, Vec n);

But with my new realization geometry/vec.h was replaced by geometry/types.h which defined all the structs for geometry types like 2D vector, 2D matrix, circle, rectangle etc. geometry/vec.h was instead included in mat.c. This has major implications for large programs where compile times often can get very high because header files are re-processed countless times. I am not claiming this is any ingenious insight of mine. It is not by a long stretch. On the contrary it should be pretty darn obvious and a lot of C programmers are probably laughing at me for pointing out such an obvious thing, but having done C++ programming for too many years might have caused some brain damage. But hopefully this was worthwhile being pointed out to other brain damaged C++ developers.

Nor am I saying that this problem can’t be solved in C++, but it requires a lot more diligence. The Visualization Toolkit (VTK) is a good example. They mandate that you only use pointers to objects. That way you can forward declare everything, except the class you inherit. Most big C++ projects probably wont realize this until it is too late, and they have by then gotten too used to using nice STL and Boost stuff which doesn’t play well this mindset.

Filed under C C++

  1. assoc posted this