tags:

views:

414

answers:

4

I have a C code base and need to programmatically identify all of the global variables used. I think that gcc can be made to produce a memory map file but don't know how and this might let me see which variables are global? Any help would be appreciated.

Cheers

A: 

Why do you need to know this? For a lot of purposes, static data (whether at file or function scope) should be grouped with the globals.

In general, globals do show up as data, not code in the linker map. Stack variables and heap-allocated variables do not. (Of course, the pointer to heap allocated data can be a global; that's just the regular distinction in C between a pointer and what it points to.)

MSalters
+1  A: 

The option to output memory map is -M with the linker, so to get it from gcc you have to use gcc .... -Xlinker -M.

Another way to to get these is to use the ctags program. It can not only tag the available functions, but also the available global variables (and does not collect the statics, this is different to memory map). As it doesnt compile everything this should also be faster than the gcc approach (if you have to compile, you would get that of course for free).

flolo
+6  A: 

You can extract such information from your object files with nm.

nm *.o | grep OBJT | grep GLOB

EDIT Command above is for Solaris' nm (SUNWbtool package). For portability, nm has a parameter to choose the output format:

nm -f [posix|bsd|sysv] *.o
philippe
The values OBJT and GLOB were not generated in the 'nm' output when I ran it but various Alphabetic identifiers were used in place. 'nm' is a GNU Development Tool if you are wondering. Try man nm on your linux dev box.
Howard May
A: 

If you have dwarfdump and your binary contains DWARF debug information (not stripped), you can check out content of .debug_pubnames DWARF section by running

dwarfdump -p mybinary | awk '{print $2}'

It will produce set of lines with names of global symbols, one per line.

qrdl