Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a string in a macro variable?

I have a macro where I pass in an argument and use that define a new variable based on the name of the input:

#define DO_X(x) char _do_x_var_ ## x; /* other things */

The problem is if I pass in a struct variable, it breaks:

DO_X(some_struct->thing)

becomes:

char _do_x_var_some_struct->thing; /* other things */

EDIT: What I want it to evaluate to is:

char _do_x_var_some_struct__thing; /* other things */

(or any valid variable name containing something similar to the input)

What I actually want is for these to work:

#define DO_X(x) for(char _do_x_var_ ## x; /*things*/)
DO_X(x){
    DO_X(y) {
        /*things*/
    }
}

DO_X(object->x){
    DO_X(object->y) {
        /*things*/
    }
}

but for these to fail:

#define DO_X(x) for(char _do_x_var_ ## x; /*things*/)
DO_X(x){
    DO_X(x) { // <-- multiple definition of _do_x_var_x
        /*things*/
    }
}

DO_X(object->x){
    DO_X(object->x) { // <-- multiple definition of _do_x_var_object__x (or whatever)
        /*things*/
    }
}

Is there some way to make this work? Maybe replacing -> with __ or something? I've found ways to concatenate, but not replace strings..

like image 591
Brendan Long Avatar asked Oct 28 '25 23:10

Brendan Long


1 Answers

You haven't found a way to rewrite arbitrary strings because macros cannot do that. Macros names have to be valid identifiers, which -> is not. The C preprocessor is very limited in what it can do. You could look into m4 for a stronger preprocessor, but you're likely headed down the wrong road.

like image 139
Jeremy W. Sherman Avatar answered Oct 30 '25 15:10

Jeremy W. Sherman



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!