简体   繁体   English

定义一个宏以将前缀 0x 添加到十六进制字符串文字

[英]Defining a macro to add the prefix 0x to a hex string literal

I am trying to get a macro to work in my c program to add 0x to a HEX literal as follows:我试图让一个宏在我的 c 程序中工作,以将0x添加到十六进制文字,如下所示:

#define BUILD ABCD0000

#define CONCAT(m, n) m ## n
#define HEX(x) CONCAT(0x, x)

const uint32_t Id = HEX (BUILD);

I get this compiler error: invalid suffix "x" on integer constant.我收到此编译器错误:整数常量上的后缀“x”无效。 Can anyone help?任何人都可以帮忙吗?

This is not the answer that you expect, but I am sorry, I have to: DON'T DO THIS!!这不是您期望的答案,但很抱歉,我必须:不要这样做!!

Why not ?为什么不 ?

  • It is misleading: The name and the syntax HEX(x) leads to think would convert x to hex, whereas it requires the argument to already be in hex.这是误导性的:名称和语法HEX(x)导致认为会将 x 转换为十六进制,而它要求参数已经是十六进制的。
  • It behaves badly: HEX(ABC00+10) would take the first part has hex but the second part still in decimal.它的行为很糟糕: HEX(ABC00+10)会将第一部分采用十六进制,但第二部分仍为十进制。 To let macros behave well with expressions, the trick is to enclose each use of a parameter between parenthesis, but this is not possible with concatenation.为了让宏在表达式中表现良好,诀窍是将参数的每次使用都括在括号之间,但这对于连接是不可能的。
  • It goes against POLA for you peer developers对于您的同行开发人员来说,这与POLA 背道而驰
  • Better get accustomed to 0x : it appears in a lot of code around there, in compiler messages, in debuggers, etc... So train your eyes instead of trying to escape.最好习惯0x :它出现在那里的很多代码中,在编译器消息中,在调试器中,等等......所以训练你的眼睛而不是试图逃避。

This being said, after having tested on a couple of compiler versions on godbolt, I could not reproduce your error.话虽如此,在 Godbolt 上对几个编译器版本进行了测试后,我无法重现您的错误。 So if you want to go on:所以如果你想继续:

  • Maybe your old compiler is disturbed by spacing (remove all spaces in macro definitions and macro uses).也许您的旧编译器被间距干扰(删除宏定义和宏使用中的所有空格)。 Or, it shouldn't, but who knows, the two x in the macro to expand?或者,它不应该,但谁知道,宏中的两个x展开?
  • Or maybe your compiler expects each token used in a macro to be valid (eg strings must be closed, literals valid, etc...).或者,您的编译器可能希望宏中使用的每个标记都是有效的(例如,字符串必须关闭,文字有效等......)。 I remember having such limitations but on very old C compilers in the 80's, perhaps 90s*我记得有这样的限制,但在 80 年代,也许是 90 年代的非常旧的 C 编译器上*

This is resolved now.现在已经解决了。 I got it working on another compiler and then realized that it was actually generating a blank for the BUILD value ie just #define BUILD我让它在另一个编译器上工作,然后意识到它实际上为 BUILD 值生成了一个空白,即只是 #define BUILD

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM