List global variables in a C program
Asked Answered
M

4

7

Is there a tool around that will list all the global variables in a C program? More specifically, is there a simple commandline tool that will do this, i.e. not a heavyweight IDE, CASE, graphical toolkit system etc., but just something that can be run like foo *.c?

Mcmillen answered 21/5, 2011 at 16:20 Comment(4)
you would need at least preprocessor, so noManicotti
most compilers have a way to output a map file which lists all the global symbols (functions and variables) and their addresses.Fetal
Doug - it's been so long since I looked at a map file, I had forgotten their existence :-) but yep, looking at the one the Microsoft compiler produces, the global variables are nicely gathered together marked 'common'. If you post that as an answer, I can mark it accepted and upvote it.Mcmillen
Or hmm, it doesn't quite - some globals aren't so marked, I don't know why, no apparent pattern to it. But nm seems to do better.Mcmillen
K
6

If you happen to compile the file on most unixes you have nm that just lists you all linker symbols. These symbols are classified in different groups (a bit platform dependent) so you should easily find out which the variables are.

Karolyn answered 21/5, 2011 at 16:46 Comment(0)
B
7
ctags -R -x --sort=yes --c-kinds=v --file-scope=no file "c:\my sources" > c:\ctagop.txt
Brynn answered 31/7, 2013 at 18:48 Comment(1)
Don't ever post one-liners without explaining (a) where to get all the programs involved and (b) what all the arguments mean.Selfreproach
K
6

If you happen to compile the file on most unixes you have nm that just lists you all linker symbols. These symbols are classified in different groups (a bit platform dependent) so you should easily find out which the variables are.

Karolyn answered 21/5, 2011 at 16:46 Comment(0)
I
5

Try ctags. Or, gcc with -aux-info. There is also gccxml and libclang but those two aren't very simple.

Inattention answered 21/5, 2011 at 16:41 Comment(0)
S
0

to list all globals (linux/gnu) for program 'foo': if the program is compiled with -g (gcc -g -o foo main.c) nm foo | grep " B " | sed -e "s/^[^B]*B//g" will list all globals, nm lists the objects, grep seperates out the global variables, and sed cleans up the presentation.

Actually most stuff I compile is with Makefiles so it is CFLAGS=-g -pg -Wextra in the Makefile, so the executable can be scanned until a 'make dist'

user1717828 on stackechange provided the grep template

Sandie answered 19/9, 2022 at 19:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.