C 预处理器,将宏的结果字符串化

发布于 2024-09-13 19:35:56 字数 342 浏览 7 评论 0原文

我想将宏扩展的结果字符串化。

我尝试过以下操作:

#define QUOTE(str) #str
#define TEST thisisatest
#define TESTE QUOTE(TEST)

TESTE 扩展为:“TEST”,而我试图获取“thisisatest”。我知道这是预处理器的正确行为,但是任何人都可以帮助我找到实现另一个的方法吗?

Using TESTE #TEST is not valid
Using TESTE QUOTE(thisisatest) is not what I'm trying to do

I want to stringify the result of a macro expansion.

I've tried with the following:

#define QUOTE(str) #str
#define TEST thisisatest
#define TESTE QUOTE(TEST)

And TESTE gets expanded to: "TEST", while I'm trying to get "thisisatest". I know this is the correct behavior of the preprocessor but can anyone help me with a way to achieve the other one?

Using TESTE #TEST is not valid
Using TESTE QUOTE(thisisatest) is not what I'm trying to do

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

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

发布评论

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

评论(2

终陌 2024-09-20 19:35:56

像这样:

#include <stdio.h>

#define QUOTE(str) #str
#define EXPAND_AND_QUOTE(str) QUOTE(str)
#define TEST thisisatest
#define TESTE EXPAND_AND_QUOTE(TEST)

int main() {
    printf(TESTE);
}

原因是当宏参数被替换到宏体中时,它们会被扩展,除非它们与 # 或 ## 预处理器运算符一起出现在该宏中。因此,str(代码中值为 TEST)不会在 QUOTE 中展开,但会在 EXPAND_AND_QUOTE 中展开代码>.

Like this:

#include <stdio.h>

#define QUOTE(str) #str
#define EXPAND_AND_QUOTE(str) QUOTE(str)
#define TEST thisisatest
#define TESTE EXPAND_AND_QUOTE(TEST)

int main() {
    printf(TESTE);
}

The reason is that when macro arguments are substituted into the macro body, they are expanded unless they appear with the # or ## preprocessor operators in that macro. So, str (with value TEST in your code) isn't expanded in QUOTE, but it is expanded in EXPAND_AND_QUOTE.

我爱人 2024-09-20 19:35:56

为了澄清一点,本质上预处理器是为了执行另一个“阶段”。即:

第一种情况:

->TESTE
->QUOTE(TEST) # preprocessor encounters QUOTE 
 # first so it expands it *without expanding its argument* 
 # as the '#' symbol is used
->TEST

第二种情况:

->TESTE
->EXPAND_AND_QUOTE(TEST)
->QUOTE(thisisatest) 
  # after expanding EXPAND_AND_QUOTE
  # in the previous line
  # the preprocessor checked for more macros
  # to expand, it found TEST and expanded it
  # to 'thisisatest'
->thisisatest

To clarify a bit more, essentially the preprocessor was made to execute another "stage". i.e :

1st case:

->TESTE
->QUOTE(TEST) # preprocessor encounters QUOTE 
 # first so it expands it *without expanding its argument* 
 # as the '#' symbol is used
->TEST

2nd case:

->TESTE
->EXPAND_AND_QUOTE(TEST)
->QUOTE(thisisatest) 
  # after expanding EXPAND_AND_QUOTE
  # in the previous line
  # the preprocessor checked for more macros
  # to expand, it found TEST and expanded it
  # to 'thisisatest'
->thisisatest
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文