Libclang 是查找匹配(或不匹配模式)的成员变量的好工具,但是有一种更简单的方法可以解决代码库中漂亮的打印指针和引用的问题,那就是使用clang-format,它是用于格式化 C/C++/Java/JavaScript/Objective-C/Protobuf 代码的工具。
Clang-format 有大量的选项,但最感兴趣的可能是PointerAlignment
,它可以具有以下值之一:Left、Right 或 Middle,它们会适当地重新格式化指针(和引用)。
您可以从在线工具之一或内置样式生成 clang-format 的新配置文件:
clang-format -style=llvm -dump-config > .clang-format
编辑该文件以设置PointerAlignment
为 Left 并运行:
clang-format main.cpp
在“不良”格式的代码上,例如:
// main.cpp
int main()
{
int a;
int* b;
int *c;
int& d;
int &d;
int * e;
const int * f;
const int * const g;
return 0;
}
我得到:
// main.cpp
int main() {
int a;
int* b;
int* c;
int& d;
int& d;
int* e;
const int* f;
const int* const g;
return 0;
}
其他设置的结果类似。
如果您确实需要从代码中执行此操作,您可以使用libformat (支持 clang-format 的库),或者您可以使用从subprocess调用 clang-format ,这就是 clang 代码库中的其他工具执行此操作的方式。