简体   繁体   中英

how to count all global variables in the cpp file

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

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 ( Bo by default) is pretty much the compiled file without removed identifiers.

  2. nm Bo : 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM