Define 预处理器指令中的字符串文字

发布于 2024-11-28 20:20:12 字数 390 浏览 4 评论 0原文

我想要在引用中使用 #define 指令。问题是:

我正在使用的嵌入式平台中有一个内置函数,它将文字汇编代码作为字符串。我想把它包装成一个宏。

__asm__("goto 0x2400");

上述内置函数处理器跳转到位置 0x2400 处的代码并开始在该地址执行(对于那些想知道的人,我正在编写一个引导加载程序,这就是为什么这是必要的)。因为地址在字符串中,所以我不能轻易替换它。我需要一种使函数通用的方法,以便我可以在任何地址开始执行代码。例如:

#define ASM_GOTO __asm__("goto X")

这不会导致正确的文本替换,因为 X 在引号中。有办法解决这个问题吗?

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 executing 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

心清如水 2024-12-05 20:20:12
#define ASM_GOTO(X) __asm__("goto " #X)

不过,这有一个小问题:

#define MAGIC_ADDRESS 0x2400
ASM_GOTO(MAGIC_ADDRESS);

导致 __asm__("goto " "MAGIC_ADDRESS");,我预计这不是您想要的。

所以,

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

可能更像它,因为在 ASM_GOTO 的扩展中,XSTRINGIZE 作用于它之前就被扩展了。

如果您还不知道,请注意,虽然预处理器的结果是 "goto " "0x2400" (两个字符串文字标记),但它们在编译期间会组合成单个字符串文字( C99 的 5.1.1.2/6)。这发生在宏扩展之后 (4),但在语义分析之前 (7)。

#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).

溺深海 2024-12-05 20:20:12

试试这个:

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

Try this:

#define ASM_GOTO(X) __asm__("goto "#X)
一个人的旅程 2024-12-05 20:20:12

您需要使用字符串化运算符。比如:

#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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文