如何从C宏的值生成一个字符串?

idfiyjo8  于 2023-05-22  发布在  其他
关注(0)|答案(3)|浏览(117)

例如,如何避免重复写入'func_name'?

#ifndef TEST_FUN
#  define TEST_FUN func_name
#  define TEST_FUN_NAME "func_name"
#endif

我想遵循Single Point of Truth规则。
C预处理器版本:

cpp --version

输出:

cpp (GCC) 4.1.2 20070626 (Red Hat 4.1.2-14)
holgip5t

holgip5t1#

He who is Shy * 给出了answer的胚芽,但只是胚芽。在C预处理器中将值转换为字符串的基本技术确实是通过'#'运算符,但是简单地音译所提出的解决方案会产生编译错误:

#define TEST_FUNC test_func
#define TEST_FUNC_NAME #TEST_FUNC

#include <stdio.h>
int main(void)
{
    puts(TEST_FUNC_NAME);
    return(0);
}

语法错误在'puts()'行-问题是源代码中的'stray #'。
在6.10.3.2C标准的www.example.com部分“#operator”中,它说:
类函数宏的替换列表中的每个# preprocessing标记后面都应跟随一个参数,作为替换列表中的下一个预处理标记。
麻烦的是,您可以将宏参数转换为字符串--但不能转换非宏参数的随机项。
所以,为了达到你所追求的效果,你肯定要做一些额外的工作。

#define FUNCTION_NAME(name) #name
#define TEST_FUNC_NAME  FUNCTION_NAME(test_func)

#include <stdio.h>

int main(void)
{
    puts(TEST_FUNC_NAME);
    return(0);
}

我不完全清楚您计划如何使用宏,以及您计划如何完全避免重复。这个稍微复杂一点的例子可能会提供更多信息。使用等同于STR_VALUE的宏是一种习惯用法,它是获得所需结果所必需的。

#define STR_VALUE(arg)      #arg
#define FUNCTION_NAME(name) STR_VALUE(name)

#define TEST_FUNC      test_func
#define TEST_FUNC_NAME FUNCTION_NAME(TEST_FUNC)

#include <stdio.h>

static void TEST_FUNC(void)
{
    printf("In function %s\n", TEST_FUNC_NAME);
}

int main(void)
{
    puts(TEST_FUNC_NAME);
    TEST_FUNC();
    return(0);
}
  • 在这个答案第一次被写出来的时候,shoosh的名字中使用了“害羞”作为名字的一部分。
hi3rlvi2

hi3rlvi22#

乔纳森·莱弗勒的解决方案奏效了。
一个完整的工作示例:

/** Compile-time dispatch

   gcc -Wall -DTEST_FUN=another_func macro_sub.c -o macro_sub && ./macro_sub
*/
#include <stdio.h>

#define QUOTE(name) #name
#define STR(macro) QUOTE(macro)

#ifndef TEST_FUN
#  define TEST_FUN some_func
#endif

#define TEST_FUN_NAME STR(TEST_FUN)

void some_func(void)
{
  printf("some_func() called\n");
}

void another_func(void)
{
  printf("do something else\n");
}

int main(void)
{
  TEST_FUN();
  printf("TEST_FUN_NAME=%s\n", TEST_FUN_NAME);
  return 0;
}

示例:

gcc -Wall -DTEST_FUN=another_func macro_sub.c -o macro_sub && ./macro_sub

输出:

do something else
TEST_FUN_NAME=another_func
mbyulnm0

mbyulnm03#

#include <stdio.h>

#define QUOTEME(x) #x

#ifndef TEST_FUN
#  define TEST_FUN func_name
#  define TEST_FUN_NAME QUOTEME(TEST_FUN)
#endif

int main(void)
{
    puts(TEST_FUN_NAME);
    return 0;
}

参考:Wikipedia的C预处理器页面

相关问题