0

Essentially, I'm simulating object-oriented programming in basic C, due to necessity. For my own convenience, I'd like to use a macro or an inline function to reduce the amount of code I need to write. For my 400+ variables, each needs a structure like

int x;
int get_x(){
    return x;
}
void set_x(int a){
    x = a;
}

I was hoping there was some intelligent way to write this as a macro oneliner, so that I can feed type foo(x) and it'll replace it with all that code. The difficulty, I think, is in using the variable x as a string, so that it can be used in function titles.

Is there some C guru out there who's come across this sort of thing before?

  • 1
    I think you need to explain some more about your motivation, because to me using `x` to represent the value seems more intuitive than `get_x()` for the simple case you present above. – jxh Jun 19 '13 at 00:16

1 Answers1

1
#define MAKE_OOP_VAR(var_type, var_name) \
var_type var_name; \
var_type get_##var_name() { return var_name; } \
void set_##var_name(var_type tmp) { var_name = tmp; } \

MAKE_OOP_VAR(int, x);

Not compile tested but off the top of my head.

Jesus Ramos
  • 22,940
  • 10
  • 58
  • 88
  • This is absolutely perfect, works like a charm. Thanks a million. What is the function of the `##`? – James Adam Buckland Jun 19 '13 at 00:21
  • @James Concatenation in macros, so that it concatenates the name of the variable to the function name instead of naming it get_var_name it will expand it to be get_x instead – Jesus Ramos Jun 19 '13 at 01:50