How to reuse the same piece of C code with different typedef within the same program?

StackOverflow https://stackoverflow.com/questions/16790303

  •  30-05-2022
  •  | 
  •  

Question

I have a dynamic array ADT whose element type is void*

// In dyn_array.h
typedef void* element;
void append(array *a, element e);
inline void set(array *a, int i, element e);
...
// dyn_array.c contains the implementation

and this is used in many parts of my program. When I am adding new features to the program, now I want a dynamic array with int element instead of void*. I know one of the solution might be making a dyn_arrayi.h and dyn_arrayi.c whose contents are almost identical to dyn_array.h and dyn_array.c, except the typedef statement and the functions' names. But that doesn't seem to be an elegant solution for me, because I am obviously repeating myself meaninglessly.

Is there a better solution so that I don't need to repeat myself? Perhaps compiling different versions of object code? How exactly would you do that? Thanks.

Was it helpful?

Solution

This is the kind of thing that C++ is better at supporting than C. Could you consider C++ instead?

Anyhow, in C you could do this: first defined dyn_array_generic.c, etc. using the ARRAY_TYPE in place of void* and adding the function postfix defined in FUNC_POSTFIX to each function name using a suitable macro, then in dyn_array.c, etc. do this:

#define ARRAY_TYPE void*
#define FUNC_POSTFIX 
#include "dyn_array_generic.c"
#undef FUNC_POSTFIX
#undef ARRAY_TYPE

and in dyn_arrayi.c, etc. do this:

#define ARRAY_TYPE int
#define FUNC_POSTFIX _int
#include "dyn_array_generic.c"
#undef FUNC_POSTFIX
#undef ARRAY_TYPE

the #undef is not strictly needed I just think it's clearer.

OTHER TIPS

Already tried macros?

You could try a simple #ifdef

#define DEFINE_MY_TYPE(tp) \
typedef (tp) elem;

#define FUNCTION_APPEND(func_name) \
void func_name(array *a, elem e);


#define FUNCTION_SET(func_name) \
void func_name(array *a, elem e);

#ifdef USE_INT
DEFINE_MY_TYPE(int)
#elif USE_VOID
DEFINE_MY_TYPE(void *)
#endif

You can define an entire function with macros.

#define FUNCTION_APPEND(func_name) \
void func_name(array *a, elem e){  \
    int a,b,c, \
    ...        \
    return 0;  \
}

FUNCTION_APPEND(append_int)

int main (int argc, char *argv[]){
{
    ....
    append_int(NULL, 0);  //using function defined with MACRO
    ...
    return 0;
}

Or, depending in how you plan to use those macros, you could try the X Macro technique (http://en.wikipedia.org/wiki/X_Macro), but Google for more information before actually use it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top