简体   繁体   中英

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:

#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. 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.
  • It behaves badly: HEX(ABC00+10) would take the first part has hex but the second part still in decimal. 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
  • 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.

This being said, after having tested on a couple of compiler versions on godbolt, I could not reproduce your error. 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?
  • 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*

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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