Question

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?

Was it helpful?

Solution

#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.

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