问题
To avoid duplication, I want to use __LINE__
in the auto-generated variable name.
#define ROUTE(path, impl) \
char * k##impl##__LINE__##_route = "{"#path":\""#impl"\"}";
But it always be treated as a normal string __LINE__
.
Even if I define it as the following, I can not get what I want:
#define ROUTE(path, impl) ROUTE_(path, impl, __LINE__)
#define ROUTE_(path, impl, line) \
char * k##impl##line##_route = "{"#path":\""#impl"\"}";
回答1:
You need one more level of nesting:
#define ROUTE(path, impl) ROUTE_(path, impl, __LINE__)
#define ROUTE_(path, impl, line) ROUTE_1(path, impl, line)
#define ROUTE_1(path, impl, line) \
char * k##impl##line##_route = "{"#path":\""#impl"\"}";
回答2:
This works:
#define CAT_(A,B) A##B
#define CAT(A,B) CAT_(A,B)
#define ROUTE(path, impl) \
char * CAT(CAT(k##impl,__LINE__),_route) = "{"#path":\""#impl"\"}";
回答3:
If you're not using the variable try "compound literals"
#include <stdio.h>
#include <time.h>
int main(void) {
// using preprocessor 'trick'
struct tm uniquenamewith__LINE__inthename = {0};
uniquenamewith__LINE__inthename.tm_year = 2019 - 1900;
uniquenamewith__LINE__inthename.tm_mon = 12 - 1;
uniquenamewith__LINE__inthename.tm_mday = 18;
time_t foo = mktime(&uniquenamewith__LINE__inthename);
// using compound literal
time_t bar = mktime(&(struct tm){.tm_year=2019-1900, .tm_mon=12-1, .tm_mday=18});
printf("foo is %lu, bar is %lu\n", (unsigned long)foo, (unsigned long)bar);
return 0;
}
See code running on ideone
来源:https://stackoverflow.com/questions/59394700/is-it-possible-to-use-line-in-the-auto-generated-variable-name-in-c