how to count all global variables in the cpp file

2019-07-19 07:36发布

Does it exist an any cpp code parser to solve this problem? For example

// 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;
  }

This file has 10 global variables : ancestor, ansv, cost, graph, M, N, p, qr, query, u

标签: c++ parsing
1条回答
地球回转人心会变
2楼-- · 2019-07-19 08:18

You could invoke the compiler and count the exported global variables with the following shell command:

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

If you remove the line count, you get their names

$ 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

Let's see how this works.

  1. g++ -O0 -c B.cpp: This calls the compiler without optimizations such that the output (B.o by default) is pretty much the compiled file without removed identifiers.

  2. nm B.o: Calls nm a tool that (quote from link) "list symbols from object files". If, for example "the symbol is in the uninitialized data section", there is a "B".

  3. We want to have global values (means uppercase) but not U, T or W. This is what the grep does.

查看更多
登录 后发表回答