问题
Background
I have a project where I have two separate products with near-identical macro names, for which I would like to create a macro-like-function to retrieve the values of the macros quickly. I have written a getTranslation
macro-function to take the literal text provided to the "function", which should be treated as a string and a string prefix (shown below).
Question
How can I accomplish this operation of taking the arguments supplied to the macro, concatenating them together (with an underscore in the middle), and treating that result as a preprocessor macro instead of a string?
Code Listing
/*******************************************************************************
* coconut.h
******************************************************************************/
#define COCONUT (PRODUCT_COCONUT)
#define COCONUT_FX_REGISTER (100)
#define COCONUT_BASE_REGISTER (101)
/*******************************************************************************
* pineapple.h
******************************************************************************/
#define PINEAPPLE (PRODUCT_PINEAPPLE)
#define PINEAPPLE_FX_REGISTER (200)
#define PINEAPPLE_BASE_REGISTER (201)
/*******************************************************************************
* test.c.
******************************************************************************/
#include <stdio.h>
#include "translation.h"
#include "coconut.h"
int main(void) {
int i = getTranslation(FX_REGISTER, COCONUT);
printf("Translation:%d.\n", i);
return 0;
}
/*******************************************************************************
* translation.h
******************************************************************************/
#define FX_REGISTER (0)
#define BASE_REGISTER (1)
#define getTranslationInternal(x, y) #y "_" #x
#define getTranslation(x, y) getTranslationInternal(x, y)
enum Products {
PRODUCT_COCONUT = 0,
PRODUCT_PINEAPPLE,
PRODUCT_MAX,
PRODUCT_INVALID = (-1)
};
Compiler Warnings
test.c: In function ‘main’:
test.c:10:45: warning: initialization makes integer from pointer without a cast [-Wint-conversion]
int i = getTranslation(FX_REGISTER, COCONUT);
^
translation.h:7:39: note: in definition of macro ‘getTranslationInternal’
#define getTranslationInternal(x, y) #y "_" #x
^
test.c:10:10: note: in expansion of macro ‘getTranslation’
int i = getTranslation(FX_REGISTER, COCONUT);
Sample Run
Translation:4195812.
回答1:
#define getTranslationInternal(x, y) y ## _ ## x
worked for me on clang, if you drop parentheses around the macro definitions.
来源:https://stackoverflow.com/questions/47442197/macro-function-to-generate-macro-with-prefix-avoid-stringification