Automatic replacement of variables #defines

I have a file with about 100 #defines in it, from 1 to 100 and each with a unique string value.

Now I'm trying to print this value, but instead of the value, I want to print that #define. For example:

#define FIRST_VALUE 1
var = FIRST_VALUE;
printf("%s", var);

and I want printf to print FIRST_VALUE, not 1.

Is there a way to do this in C? Or should I just write over 100 blocks of code inside a switch statement?

+3
source share
3 answers

After talking with one of my TAs at school, we decided that the best way to do this was to write an AWK script to process the header file and automatically generate all the necessary case statements.

Thanks guys!

+1

stringification , :

  #define FIRST_MACRO
  #define MACRO_TO_STRING(x) #x

  #include <stdio.h>

  main() {
     printf("%s\n",  MACRO_TO_STRING(FIRST_MACRO));
  }

:

FIRST_MACRO
+12

, , , , "" . , , , , , .

. enums.h:

#ifndef ENUMS_H
#define ENUMS_H

#ifndef ENUM
#define ENUM(name,val) enum { name = val };
#endif

ENUM(ONE,1)
ENUM(TWO,2)
ENUM(THREE,3)

#endif /* ENUMS_H */

-, .c, / .h . enums.c:

#include 
#include 

typedef struct {
        char *str;
        int val;
} DescriptiveEnum;

static DescriptiveEnum enums[] = {
#define ENUM(name,val) { #name, val },
#include "enums.h"
};
#define NUM_ENUMS (sizeof(enums)/sizeof(enums[0]))

char *enum_to_str(int val)
{
        int i;
        for (i=0;i<NUM_ENUMS;i++) {
                if (enums[i].val == val) return enums[i].str;
        }
        return "";
}

, . main.c:

#include <stdio.h>
#include <stdlib.h>
#include "enums.h"

char *enum_to_str(int val);

int main(int argc, char *argv[])
{
        int val;

        val = ONE;

        printf("%d %s\n",val,enum_to_str(val));

        return EXIT_SUCCESS;
}
0

Source: https://habr.com/ru/post/1702872/


All Articles