首页 > 解决方案 > 使用 clang 预处理器将所有宏声明作为字符串查找?

问题描述

#include<stdio.h>

#define engine_exhaust_gas_temperature_raw 100
#define engine_exhaust_gas_temperature_scaled 20

#define Sum(x, y) ( ( x )+ ( y ) )


int main(){
    
    printf("%d",engine_exhaust_gas_temperature_raw);

    return 0;
}

我正在研究 MISRA C规则 5.4 宏标识符应该是不同的,为此我需要 C 程序中定义的所有宏的名称列表作为字符串。

例如:在上面的代码中,我需要:

[“engine_exhaust_gas_temperature_raw”,“engine_exhaust_gas_temperature_scaled”,“总和”]

有什么方法可以使用 clang AST 获取此列表?

我发现我们可以使用 clangs https://clang.llvm.org/doxygen/classclang_1_1Preprocessor.html预处理器类来获取宏的迭代器,但即使这样也不会为我产生任何输出。我在下面的代码中使用了它。我在这里想念什么?

bool distinct_macro_identifier(CompilerInstance *C_I, ASTContext *Context){
  
  auto st= C_I->getPreprocessor().macro_begin()->getFirst()->getName();

  auto x= C_I->getPreprocessor().macro_begin()->first;

  llvm::outs()<<x->getName()<<"\n";

  auto p= C_I->getPreprocessor().getMacroInfo(x);

  p->dump();

  return true;
}

标签: clangllvmabstract-syntax-treellvm-clang

解决方案


您可以使用以下命令编译它:

clang++ -E -dM  -nostdlib file.cpp

推荐阅读