用 define C 替换函数调用(而不是声明)

Replacing function call (and not declaration) with define C

我尝试使用 define 来替换函数调用,但我找不到如何只替换调用而不替换声明的方法。

IE:

#define test(); printf("worked\n");

void test()
{
printf("how sad ?\n");
}

int main()
{
test();
}

我无法在函数之后创建我的定义(项目规则)

问题是:我希望定义中 "test()" 之后的分号仅替换调用,但它也替换声明。

我试过 google 但什么也没有,这真的可能吗?奇怪的是它没有采取文字表达。

注意几点:

  • #define 不需要 大括号 () - 仅在需要处理参数时才使用它们
  • 语法不包含分号:#define test printf
  • 像这样调用像 printf() 这样的函数(有点模糊)可能会有风险,特别是如果调用者不希望他们的字符串用作格式字符串。更喜欢#define test(msg) printf("%s", msg)
  • #define test ...之后,预处理器将笨拙地替换test所有个实例——因此函数声明实际上是 void printf("worked\n"); { ... }

结果应该是:

#include <stdio.h>

#define test(msg) printf("%s\n", msg)

void main(void) {
    test("hello");
}

或:

#include <stdio.h>

void test(const char *msg) {
    printf("%s\n", msg);
}

void main(void) {
    test("hello");
}

如果您尝试使用 #define 来重定向函数调用,那么您必须使用不同的符号...例如:

#include <stdio.h>

/* Comment / uncomment this to change behaviour */
#define REDIRECT_TEST

#ifdef REDIRECT_TEST
#  define my_test(msg) printf("REDIRECTED:%s\n", msg)
#else
#  define my_test      test    
#endif

void test(const char *msg) {
    printf("%s\n", msg);
}

void main(void) {
    my_test("hello");
}

您应该在单独的头文件中定义。并且定义不应包括分号。 所以你的代码应该是这样的:

replace_test.h:

#define test() dummy_test()

test.h:

void test();

test.c:

void test()
{ your test code}

dummy.c:

void dummy_test()
{
 your dummy code here (printf("worked!"); etc.
}

program.c:

//decide which behavior you want, either include replace_test.h or test.h header
#include "replace_test.h"
//#include "test.h"

int main()
{
   test();
}

printf 有一个 "variadic arguments"。如果您不使用 q/a 中的任何解决方案,有时您会遇到问题:"How to wrap printf() into a function or macro?"

像这样的提示,例如:

#define MY_PRINTF(...) printf(__VA_ARGS__)

或者这个:

#define MY_PRINTF(f_, ...) printf((f_), ##__VA_ARGS__)