控制 CPP 预处理器的执行

Controlling the executions of CPP Preprocessor

本文关键字:执行 处理器 预处理 CPP 控制      更新时间:2023-10-16

我正在使用标准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++

例如,您的断言标头可能看起来像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("Tralalan");
}
int main (void) {
foo(1);
return 0;
}

使用上述技巧,您可以运行cpp -DASSERT_DEBUG test.c

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

我已经使用 #pragma 毒TC_ASSERT_EQ语句来传递该行而无需预处理。