Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you prevent names from colliding in C

Let's say I have a two files : stack.h and queue.h. Both want to implement the function add(). If I include stack.h and queue.h in the same main.c for example, there will be a collision.

What is the recommended way to implement the add() function in both files?

like image 423
Gradient Avatar asked Oct 20 '25 02:10

Gradient


1 Answers

If you already have a queue and a stack implementation tested, and referred to elsewhere.. you can do some preprocessor tricks like this:

#define _STACK
#define _QUEUE

#ifdef _QUEUE
#define add queue_add
  #include "queue.h"
#undef add
#endif

#ifdef _STACK
#define add stack_add
  #include "stack.h"
#undef add
#endif

int main()
{
   stack_add();
   queue_add();
}

My advice is - refactor the code base to use non-clashing naming convention instead of generic function names like add and subtract and the rest.

If you are a fan of object oriented programming style and like the whole "add", "modify" concept then use function pointers inside the queue and stack structure.

#define TYPE int

typedef struct tagStruct{
   TYPE *dataBuffer;
   void (*add)(TYPE data);
   void (*modify)(TYPE data, int index);
   void (*deleteEverything)()
}stack;

and in the init(stack) method, assign add(), modify() and deleteEverything() to different functions that have no name-collision(likewise for queue)

Then you begin to see stack and queue as ENTITIES rather than bunch-of-functions.

You can then do this:

stack stc;
init(stc); /*sets up the function pointers*/
stc.add(10);
stc.modify(30,0);
stc.deleteEverything(); 
like image 131
Aniket Inge Avatar answered Oct 21 '25 17:10

Aniket Inge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!