我正在尝试分析一些第三方代码,我对在给定源(.c 和 .h)中声明+定义的所有数组感兴趣。了解在移植到嵌入式系统时是否浪费了一些内存很有趣。
我可以假设只使用标准类型,即 char、int、long、float、double。
这是我想要查找的示例:
char message[100];
int tag[MY_PERSONAL_TAG_SIZE];
double vald[2] ={1.0,1.1};
在一位同事的大力支持下,我尝试了以下方法,但出现了一些误报:
egrep -e '(char|int|long|short|float|double)[ \t]*[^ \t)]+[ \t]*\[[^ \t]+\]' *
这也发现(它不应该):
wordTable = &intTable[0];
MyFunction (MyPointer* foo, int *bar, int code[4], int add[4], char *Mystring[4]) {
我猜正则表达式还会发现其他一些误报,并且可能会遗漏一些它应该找到的定义。所以我很乐意听到任何建议。谢谢。
最佳答案
我建议使用 clang-query
作为 regex
的替代方法。下面是一个示例,展示了 clang-query
的功能。
两个文件 test.h
和 test.cpp
与问题类似。
$ cat ~/CPP/test.h
1 int x[10], y, z[10];
$ cat ~/CPP/test.cpp
1 #include "test.h"
2
3 #define MY_PERSONAL_TAG_SIZE 10
4
5 struct MyPointer;
6
7 void MyFunction (MyPointer* foo, int *bar, int code[4], int add[4], char *Mystring[4])
8 {
9 }
10
11 int main()
12 {
13 char message[100];
14 int tag[MY_PERSONAL_TAG_SIZE];
15 double vald[2] ={1.0,1.1};
16 int a[10], b, c[30];
17
18 return 0;
19 }
使用 test.cpp
运行 clang-query
并查询数组声明。
$ ./clang-query ~/CPP/test.cpp --
clang-query> help
Available commands:
match MATCHER, m MATCHER Match the loaded ASTs against the given matcher.
set bind-root (true|false) Set whether to bind the root matcher to "root".
set output (diag|print|dump) Set whether to print bindings as diagnostics,
AST pretty prints or AST dumps.
clang-query> match varDecl(hasType(arrayType()))
Match #1:
~/CPP/test.h:1:1: note: "root" binds here
int x[10], y, z[10];
^~~~~~~~~
Match #2:
~/CPP/test.h:1:1: note: "root" binds here
int x[10], y, z[10];
^~~~~~~~~~~~~~~~~~~
Match #3:
~/CPP/test.cpp:13:5: note: "root" binds here
char message[100];
^~~~~~~~~~~~~~~~~
Match #4:
~/CPP/test.cpp:14:5: note: "root" binds here
int tag[MY_PERSONAL_TAG_SIZE];
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Match #5:
~/CPP/test.cpp:15:5: note: "root" binds here
double vald[2] ={1.0,1.1};
^~~~~~~~~~~~~~~~~~~~~~~~~~~
Match #6:
~/CPP/test.cpp:16:5: note: "root" binds here
int a[10], b, c[30];
^~~~~~~~~
Match #7:
~/CPP/test.cpp:16:5: note: "root" binds here
int a[10], b, c[30];
^~~~~~~~~~~~~~~~~~~
7 matches.
clang-query>
关于c++ - 如何使用正则表达式查找 C 文件中的所有数组声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25089465/