How to define a define in C?

安稳与你 提交于 2019-12-19 12:49:12

问题


Is it possible to write a #define that defines a #define?

For example:

#define FID_STRS(x) #x
#define FID_STRE(x) FID_STRS(x)
#define FID_DECL(n, v) static int FIDN_##n = v;static const char *FIDS_##n = FID_STRE(v)

But instead:

#define FID_DECL2(n, v) #define FIDN_##n v \
                               FIDS_##n FID_STRE(v)

FID_DECL works fine but creates two static variables. Is it possible to make FID_DECL2 work and having define two defines?


回答1:


No; preprocessing is performed in a single pass. If you want or need more advanced behavior, consider using another tool to preprocess the source, like m4.

Further, the # in the replacement list (at the beginning of #define FIDN... would be parsed as the # (stringize) operator: the operand of this operator must be a named macro parameter, which define is not.




回答2:


No while defining macros u should take care of one thing that macro should not call itself (reccursively) either directly or indirectly.

I know two static variables consuming 8 bytes will be expansive for u.

I have solution over it

#define FID_STRS2(x) #x
#define FID_STRE(x) FID_STRS2(x)
#define FID_DECL(n, v) static int FIDN_##n = v;static const char *FIDS_##n = FID_STRE(v)

Just rename them going reccursive



来源:https://stackoverflow.com/questions/5144042/how-to-define-a-define-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!