Abstract Data Types in C
- Interface declares operations, not data structure
- Implementation is hidden from client (encapsulation)
- Use features of programming language to ensure encapsulation
Common practice
- Allocation and deallocation of data structure handled by module
- Names of functions and variables begin with <modulename>_
- Provide as much generality/flexibility in interface as possible
- Use void pointers to allow polymorphism
A simple exmaple is shown below for your reference, but a little change as we don't want to dynamic memory.
#ifndef COMMON_TIMER_H_ #define COMMON_TIMER_H_ #include <stdint.h> #include <stdbool.h> typedef struct { uint32_t period; /* unit ms */ uint32_t endTick; /* the tick of end */ }MsTimerT; void timer_create(MsTimerT* timer, uint32_t period); bool timer_expired(const MsTimerT* timer); void timer_free(MsTimerT* timer); #endif /* COMMON_TIMER_H_ */
#include "common/timer.h" /* system tick every 10ms*/ #define SYSTEM_TICK_TIME (10) uint32_t gSystemTick = 0; void timer_create(MsTimerT* timer, uint32_t period) { timer->endTick = gSystemTick + period/SYSTEM_TICK_TIME; } bool timer_expired(const MsTimerT* timer) { return (gSystemTick >= timer->endTick); } void timer_free(MsTimerT* timer) { timer->endTick = 0; timer->period = 0; }
MsTimerT* timer,