I want to have a list of all the variables I have defined in a code in C. Is there a built-in method in C to perform this task?
-
2No. This kind of capability is part of what is called reflection in other languages and C does not have it. See also https://stackoverflow.com/questions/1353022/reflection-support-in-c – May 10 '21 at 20:10
-
1No, variable names in C are a convenience for the user. You might be able to use a tool or IDE to read the C code and find all the variables. However, generally you don't need. What are you trying to solve? – Schwern May 10 '21 at 20:10
-
Are you asking for a method that operates in the program itself or a tool outside the program that examines the source code? – Eric Postpischil May 10 '21 at 20:12
-
Maybe this could help? [Printing all global variables/local variables in gdb?](https://stackoverflow.com/q/6261392) – mediocrevegetable1 May 10 '21 at 20:16
-
Open the linker map file and parse it:) – Martin James May 10 '21 at 21:37
2 Answers
If you want to use the list in C program where variables are defined directly, you have to make a list(maybe a string array) and add name to the list every time you are defining a new variable. And there is no built-in method in C to get the variable name base on its address, because variable names will be totally erased after compile in the range of itself. So names in list have to be typed manually.
Or you can use some tools to screen variables out of program, a example using ctags on Linux bash is:
ctags --c-kinds=lv -f - <YOUR_C_SOURCE_FILE_NAME> | cut -d$'\t' -f1
ctags can also get the complete definition statement. Read the manual of ctags for more details.

- 80
- 5
Is there a built-in method in C to perform this task?
No, there is not. C language is a language without reflection. It is not possible to inspect it's own source code.
You may write a parser in C that will parse the source code of your program and extract the information from that.

- 120,984
- 8
- 59
- 111