如何计算 CPP 文件中的所有全局变量

how to count all global variables in the cpp file

本文关键字:全局变量 文件 CPP 何计算 计算      更新时间:2023-10-16

是否存在任何cpp代码解析器来解决此问题?例如

// B.cpp : Defines the entry point for the console application.
//
#include<iostream>
#include<vector>
#include<algorithm>
size_t N,M;
const size_t MAXN = 40000;
std::vector<std::pair<size_t,size_t> > graph[MAXN],query[MAXN],qr;
size_t p[MAXN], ancestor[MAXN];
bool u[MAXN];
size_t ansv[MAXN];
size_t cost[MAXN];
size_t find_set(size_t x){
   return x == p[x] ? x : p[x] = find_set(p[x]);
}
void unite(size_t a, size_t b, size_t new_ancestor){
}
void dfs(size_t v,size_t ct){
}
int main(int argc, char* argv[]){
return 0;
  }

这个文件有10个全局变量:祖先ansv成本M,N,p,qr查询u

您可以使用以下 shell 命令调用编译器并计算导出的全局变量:

$ g++ -O0 -c B.cpp && nm B.o | grep ' B ' | wc -l
10

如果删除行数,则会得到他们的名字

$ g++ -O0 -c B.cpp && nm B.o | egrep ' [A-Z] ' | egrep -v ' [UTW] '
00000004 B M
00000000 B N
00111740 B ancestor
00142480 B ansv
00169580 B cost
00000020 B graph
000ea640 B p
000ea620 B qr
00075320 B query
00138840 B u

让我们看看这是如何工作的。

  1. g++ -O0 -c B.cpp :这调用编译器而不进行优化,因此输出(默认情况下B.o)几乎是没有删除标识符的已编译文件。

  2. nm B.o :调用 nm 一个工具(引用自链接)"列出对象文件中的符号"。例如,如果"交易品种在未初始化的数据部分中",则存在"B"。

  3. 我们希望有全局值(表示大写),但不是 U、T 或 W。这就是 grep 所做的。