Compiler Dialects
The example listings I've presented are for Microsoft's VC7 compiler, mainly because the Visual C/C++ package is fairly common and has an excellent debugger. Other compilers may require small changes. For example, the GCC compiler versions typically provide the memcpy
prototype in the string.h header file rather than the memory.h file.
Most compilers will give you incompatible type warnings when referencing parental structures with derived class names. While these can be safely ignored, they can also be simply fixed with a cast to the base class structure; for example:
I use the standard library memcpy
in the macros. On some microprocessors, particularly those with a Harvard architecture, the compiler may require special directions when declaring the class vtable
instance and copying it from ROM to RAM. Check this out as, otherwise, you will find the compiler copies the instance to RAM before your program runs as part of data initialization, and then memcpy
simply copies it from one place in RAM to another.
Conclusion
I have presented a fairly simple method for creating classes in C. The code is transparent and regular, in that the method can apply to both standalone and inheritable classes with no change in syntax and little additional code. An inherited class need only call the base class constructor to be fully initialized. The ROM footprint is hardly different from a carefully modularized traditional C method, with the advantage of an obvious class structure.
While not a problem in itself, the fact that the class vtable
definition and its instance are in two different places means that you must take care they always match. This is particularly so when adding new functions to an existing design.
In a typical small embedded system, classes are created early and rarely destroyed, in part to ensure the heap does not become fragmented over the months or years between resets, but also because in most cases all classes are in use all the time. If your app is dynamically creating and destroying classes, you need to be sure of your compiler's heap management. My recommendation is to get all heap setup over and done with during initialization.
Ron designs software and hardware for embedded systems. He can be reached at [email protected].