开发者

String literals in Define preprocessor directive

I would like to the #define directive inside of a quotation. Here's the problem:

There is a built-in function in the embedded platform that I'm using that takes literal assembly code as a string. I would like to wrap this into a macro.

__asm__("goto 0x2400");

The above built-in function the processor jumps to the code at location 0x2400 and starts execut开发者_如何学JAVAing at that address (for those wondering, I'm writing a bootloader which is why this is necessary). Because the address is in the string, I cannot easily replace it. I need a way to make the function generic so that I can start executing code at any address. For example:

#define ASM_GOTO __asm__("goto X")

This will not result in a correct text replacement because the X is in quotes. Is there a way around this?


#define ASM_GOTO(X) __asm__("goto " #X)

This has a slight problem, though:

#define MAGIC_ADDRESS 0x2400
ASM_GOTO(MAGIC_ADDRESS);

Results in __asm__("goto " "MAGIC_ADDRESS");, which I expect isn't what you want.

So,

#define STRINGIZE(X) #X
#define ASM_GOTO(X) __asm__("goto " STRINGIZE(X))

is probably more like it, since in the expansion of ASM_GOTO, X gets expanded before STRINGIZE acts on it.

If you didn't already know, be aware that although the result from the preprocessor is "goto " "0x2400" (two string literal tokens), they're combined during compilation into a single string literal (5.1.1.2/6 of C99). This occurs after macros are expanded (4), but before semantic analysis (7).


Try this:

#define ASM_GOTO(X) __asm__("goto "#X)


You need to use the stringize operator. Something like:

#define ASM_GOTO(x) __asm("goto " #x)

should do what you need it to do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜