控制 CPP 预处理器的执行

Controlling the executions of CPP Preprocessor

我正在使用标准 CPP 来预处理任何 C/CPP 文件。 我正在使用以下命令进行预处理:

cpp -idirafter <path_to_header_files> -imacros <sourcefile> <source_file> > <destination_file> 

以上命令将所有宏替换为头文件中定义的相应实现。

如果我想要一些包含特定字符串(例如 ASSERT)的特定宏,则不应由 cpp 预处理器替换。即,如果某些头文件中定义的名称为 TC_ASSERT_EQ 或 TC_ASSERT_NEQ 的任何宏不应被预处理器替换。

有什么办法可以控制吗?

您可以使用预定义的宏来解决此问题。您可以使用 -D 参数

将不同的定义传递给 cpp 和 gcc/g++

例如你的断言 header 可以看起来像 my_assert.h:

#ifndef __my_assert_h__
#define __my_assert_h__

#if defined  ASSERT_DEBUG
 #define my_assert(expr) my_assert(expr) /* please dont touch my assertions */
#else
 #define my_assert(expr) ((void)0U)      /* Your assertion macro here */
#endif /* ASSERT_xxx */

#endif /* #ifndef __my_assert_h__ */

并且您的源文件可以像以前一样。例如test.c:

#include "my_assert.h"
#include <stdio.h>

void foo (int p) {
   my_assert(p==1);
   puts("Tralala\n");
}

int main (void) {
   foo(1);
   return 0;
}

通过上面的技巧你可以运行 cpp -DASSERT_DEBUG test.c

虽然编译仍然像以前一样工作。 gcc test.c

我已经使用#pragma poison TC_ASSERT_EQ 语句在没有预处理的情况下通过了行。