C x-macro with with C-style strings (const char*) include unexpected quotes when used

54 Views Asked by At

My first foray into x macros seems to be progressing well, but I'm stumped on one point which the below code and output shows. Basically, the part that's not working the way I want it to is creating pointers to C-style strings where what's pointed to does not include quote characters. The below code compiles with no errors or warnings in Visual Studio, but the output includes unwanted quote characters. I can't find any way to get the program to build if I don't include the quote where I define the x macros. Can anyone show me how to change the source such that the output doesn't include these unwanted quote characters (but includes everything else as shown)?

#include <map>
#include <stdio.h>

#define rinfo \
  X( REG1, 10 )   \
  X( REG2, 20 )   \
  X( REG3, 33 )   \

enum class RNAME {
#define X(NAME,VALUE) RNAME_ ## NAME = __COUNTER__,
    rinfo
#undef X
};

const char* const rnames[] = {
#define X(NAME,VALUE) (const char* const) "\"" #NAME "\"",
    rinfo
#undef X
};

std::map<std::string, RNAME> rmap = {
#define X(NAME,VALUE) { "\"" #NAME "\"", RNAME::RNAME_ ##NAME },
    rinfo
#undef X
};

typedef struct {
    RNAME regname;
    const char* name;
    uint32_t value;
}regx_t;

regx_t regs[] = {
#define X(NAME,VALUE) { RNAME::RNAME_ ## NAME, rnames[ (int)RNAME::RNAME_ ## NAME ], VALUE },
    rinfo
#undef X
};

int main(int argc, char *argv[]){
    int nErrors = 0;
    int n = sizeof(rnames) / sizeof(const char*);

    for (int i = 0; i < n; i++) {
        std::map<std::string, RNAME>::iterator it;
        it = rmap.find(rnames[i]);
        if (it != rmap.end()) {
            int index = (int)it->second;
            printf("rname[%d] = %s = %u = %s\r\n", i, 
                        rnames[i], 
                        regs[index].value, 
                        regs[index].name);
        }
        else {
            ++nErrors;
        }
    }

    printf("RNAME::RNAME_REG1 = %d\n", RNAME::RNAME_REG1);
    printf("RNAME::RNAME_REG2 = %d\n", RNAME::RNAME_REG2);
    printf("RNAME::RNAME_REG3 = %d\n", RNAME::RNAME_REG3);

    printf("%d errors found\n", nErrors);

    return 0;
}

This is the output the program creates as-is.

rname[0] = "REG1" = 10 = "REG1"
rname[1] = "REG2" = 20 = "REG2"
rname[2] = "REG3" = 33 = "REG3"
RNAME::RNAME_REG1 = 0
RNAME::RNAME_REG2 = 1
RNAME::RNAME_REG3 = 2
0 errors found
0

There are 0 best solutions below