1

I am trying to stringify the substitution (evaluation) of a macro concatenation. For example:

#include <stdio.h>

#define FOO_ONE 12
#define FOO_TWO 34
#define BAR_ONE 56
#define BAR_TWO 78

#define MAKE_MAC(mac) // ... what to do here?

void main(int argc, char *argv[])
{
    printf("FOO: " MAKE_MAC(FOO) "\n");
    printf("BAR: " MAKE_MAC(BAR) "\n");
}

The result I am seeking is:

FOO: 1234
BAR: 5678

I tried a few forms, I think the best attempt is this:

#define STRINGIFY(mac) #mac
#define CONCAT(mac1, mac2) STRINGIFY(mac1 ## mac2)
#define MAKE_MAC(mac) CONCAT(mac, _ONE) CONCAT(mac, _TWO)

But, it only gets me this far:

FOO: FOO_ONEFOO_TWO
BAR: BAR_ONEBAR_TWO

So, how can I add the extra step of evaluation of the resulting concatenated macro, before it gets stringified?

ysap
  • 7,723
  • 7
  • 59
  • 122
  • Possible duplicate of [Concatenate int to string using C Preprocessor](https://stackoverflow.com/questions/5459868/concatenate-int-to-string-using-c-preprocessor) – 0andriy May 29 '18 at 22:13
  • @0andriy - I don't think it is the same case - in my question, the value is assigned to a macro name which is itself the result of the concatenation of two parts. In your suggestion, each name evaluates to a separate value, and the two are then concatenated. – ysap May 29 '18 at 22:27
  • 1
    Two answers below are exactly what that Q is about. So, it's __exact__ duplication. – 0andriy May 29 '18 at 22:28
  • @0andriy - again, I don't think so. It is possible that the answers here solve the other problem as well, but the question itself, as much as my understanding of the other problem is, is different. I could be wrong, though. – ysap May 29 '18 at 22:52
  • I barely see the difference in the expected output and what any of proposed answers here. And answers here are repeating what is duplicated in the link I had provided. – 0andriy May 29 '18 at 22:54

2 Answers2

3

Try this:

#include <stdio.h>

#define FOO_ONE 12
#define FOO_TWO 34
#define BAR_ONE 56
#define BAR_TWO 78

#define STRINGIFY(arg) #arg
#define CONCAT(arg1, arg2) STRINGIFY(arg1) STRINGIFY(arg2)

#define MAC(arg) CONCAT(arg##_ONE, arg##_TWO)

int main(){

    printf("FOO: " MAC(FOO) "\n");
    printf("BAR: " MAC(BAR) "\n");

    return 0;
}

My output:

FOO: 1234
BAR: 5678
ysap
  • 7,723
  • 7
  • 59
  • 122
bobra
  • 615
  • 3
  • 18
  • Thanks. Needed a few adjustments to my particular case, but this sent my in the right direction. – ysap May 29 '18 at 23:17
2

You need to defer stringification by introducing a layer of indirection:

#define STRINGIFY_X(x) #x
#define STRINGIFY(x) STRINGIFY_X(x)
#define MAKE_MAC(mac) STRINGIFY(mac ## _ONE) STRINGIFY(mac ## _TWO)

live example on wandbox.org

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416