2008-10-12 64 views

回答

67

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()'这一行 - 问题是来源中的'流浪'。

在C标准的第6.10.3.2,“#操作符”,它说:

Each # preprocessing token in the replacement list for a function-like macro shall be followed by a parameter as the next preprocessing token in the replacement list.

麻烦的是,你可以宏参数转换为字符串 - 但你不能随意转换不是宏参数的项目。

因此,要达到您所追求的效果,您绝对不得不做一些额外的工作。

#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害羞’作为名称的一部分。

-2

#define TEST_FUN_NAME #FUNC_NAME

看到here

+2

它不起作用。看到我的答案。 – jfs 2008-10-12 20:30:51

+2

这确实是不正确的 - 另见我的答案。它有4个选票也是令人惊讶的。麻烦的是,如果你没有仔细考虑,它看起来可能或多或少是正确的。 – 2008-10-12 20:36:13

0
#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; 
} 

参考:维基百科的页面C preprocessor

+1

它也不起作用。看到我的答案。 – jfs 2008-10-12 20:34:32

12

@Jonathan Leffler:谢谢。你的解决方案有效

一个完整的工作示例:

/** 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 
相关问题