0

I want to create a define using macro expansion. The crated define shall hold the value of an other define. :)

Example:

#define ONE            1
#define TWO            2
#define MACRO(x, y)    ...
...
#define MACRO_1_2      3

My question is: how can I resolve / use the value of a define in macro expansion?

I have tried to use

#define TEST_MACRO_V2(x, y)      TEST_MACRO_V2_"x"_"y"

, but I get the following error:

main.c:18:34: error: ‘TEST_MACRO_V2_’ undeclared (first use in this function) #define TEST_MACRO_V2(x, y) TEST_MACRO_V2_"x"_"y"

My test code:

#include <stdio.h>

#define ONE   1
#define TWO   2

#define TEST_MACRO_V1(x, y)      TEST_MACRO_V1_##x##_##y
#define TEST_MACRO_V1_ONE_TWO    3

//#define TEST_MACRO_V2(x, y)    TEST_MACRO_V2_##('x')##_##('y')  -> this version does not work
#define TEST_MACRO_V2(x, y)      TEST_MACRO_V2_"x"_"y"
#define TEST_MACRO_V2_1_2        4

int main()
{
    printf("Test Macro V1: %d\n", TEST_MACRO_V1(ONE, TWO));
    printf("Test Macro V2: %d\n", TEST_MACRO_V2(ONE, TWO));

    return 0;
}

Note: TEST_MACRO_V1 works fine. I need TEST_MACRO_V2.

4
  • What do you need to do with V2 that you can't do with V1? Commented Feb 9, 2020 at 20:47
  • :) The solution shall be independent from the name of macro argument. It means, the user can use other define name, but this defines have always the same value, like 0,1,2 … So, in the “end define” I need the values of the defines used in the macro call. Commented Feb 9, 2020 at 20:52
  • It's not clear what you are asking. Please post exactly what the expected expansion of TEST_MACRO_V2(ONE, TWO) should be, or what the expected output is of the program you posted Commented Feb 9, 2020 at 21:18
  • Also explain what is the point of MACRO_1_2 , TEST_MACRO_V1_ONE_TWO and TEST_MACRO_V2_1_2 ? Commented Feb 9, 2020 at 21:19

1 Answer 1

1

I tried this on ideone.com:

#include <stdio.h>

#define ONE   1
#define TWO   2

#define TEST_MACRO_HELPER(x, y) TEST_MACRO_##x##_##y
#define TEST_MACRO(x, y)        TEST_MACRO_HELPER(x, y)
#define TEST_MACRO_1_2          4

int main()
{
    printf("Test Macro: %d\n", TEST_MACRO(ONE, TWO));
    return 0;
}

Output:

Test Macro: 4
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.