0

I am implementing a generic Hash Table in C using macros.

As one example, I defined key, value types as

#define h_key_type int 
#define h_val_type int

Then I defined put function as:

#define H_PUT(key_type, val_type) \
                void key_type##_put(...)

H_PUT(h_key_type, h_val_type);

However, after preprocessing the processed source codes become

void h_key_type_put(...)

Even I changed the function declaration as:

#define H_PUT() \
           void h_key_type##_put(...)

it's still replaced as:

 void h_key_type_put(...)

So I have to use

#define H_PUT(key_type, val_type) \
                void key_type##_put(...)

H_PUT(int, int)

to make it work.

But it's not convenient since I either have to introduce a gigantic define block, or I have to type key, value types for each function, which is not elegant.

Any ideas?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • No the recommended "duplicate" solution doesn't work. by using str(s) #s, the token of s becomes "4", given #define foo 4, xstr(foo). Obviously, "int"_put is not valid. – Qu Xinquan Jul 12 '15 at 18:52
  • You're looking at the wrong duplicate. The one about stringifying in C++ is obviously (to my mind) not relevant, but I can't undo the fact that it was suggested. You need token concatenation, which is the other question. – Jonathan Leffler Jul 12 '15 at 18:55
  • `#define H_PUT(key, val) H_EXPANDED_PUT(key, val)` and `#define H_EXPANDED_PUT(key_type, val_type) void key_type ## _put(...)`, and then `H_PUT(h_key_type, h_val_type);` (along with the first two `#define` lines from the question). Of course, in C you can't have a function which only takes ellipsis `...` as an argument; you must have at least one fixed argument. If you're coding in C++, you should be using templates, not macros, to generate the functions. – Jonathan Leffler Jul 12 '15 at 19:00
  • Thank! I think it works in that way. – Qu Xinquan Jul 12 '15 at 19:00

0 Answers0