C preprocessor: stringizing multiple levels of function-like macros

42 Views Asked by At

I'm working with multiple levels of macros where I rely on stringification of the parameters. My own functions have quite a few parameters already and stringizing them effectively doubles the number of parameters. Not the end of the world, but am wondering if there's a better/cleaner way to pass the information I need using the preprocessor.

Here's a basic version of my own code. You can see that to pass both the macro's name and numerical value through the macros, I need to pass one parameter for each.

https://godbolt.org/z/eMvaa5rs1

#define ID_1                0x12340000 | 0x00005678
#define func2(val)          printf("func2 valname: %s, valstr: 0x%x\n", #val, val)
#define func3(val_str, val) printf("func3 valname: %s, valstr: 0x%x\n", val_str, val)

#define func1a(val) func2(val)
#define func1b(val) func3(#val, val)

#define FUNCTION(value) printf("Name: %s \nValue: %i", #value, value)

int main(void){
    func1a(ID_1);
    func1b(ID_1);
}

output:

func2 valname: 0x12340000 | 0x00005678, valstr: 0x12345678
func3 valname: ID_1, valstr: 0x12345678

The output from func3 is what I'm looking for, but without passing twice as many parameters, I can't seem to accomplish this. I think this is the only way, but I figured it wouldn't hurt to ask.

Hopefully at the very least, this helps someone what's happening when using stringized parameters.

Thanks!

0

There are 0 best solutions below