Reputation: 27
For example,I define a variable
int a=5;
I know the 5
is stored in the stack, but where is a
stored?
Please help
Upvotes: 2
Views: 838
Reputation: 7132
Here is a complete minimal example that demonstrates @eerorika's answer about the debug information (here, in ELF files):
$ cat main.cpp
int main(int argc, char **argv)
{
int whereIsMyVar = 5;
return whereIsMyVar;
}
And compiling it without optimizations (-O0
), and with debug info (-g
):
$ g++ -g -O0 main.cpp -o main
Now let's see what went on with objdump
:
$ objdump -D -S main > main.asm
$ sed -n "378,389p" main.asm
00000000000005fa <main>:
int main(int argc, char **argv)
{
5fa: 55 push %rbp
5fb: 48 89 e5 mov %rsp,%rbp
5fe: 89 7d ec mov %edi,-0x14(%rbp)
601: 48 89 75 e0 mov %rsi,-0x20(%rbp)
int whereIsMyVar = 5;
605: c7 45 fc 05 00 00 00 movl $0x5,-0x4(%rbp) <--- there is your assignment !
return whereIsMyVar;
60c: 8b 45 fc mov -0x4(%rbp),%eax
}
Now let's use the addr2line
utility to easily extract the source code location corresponding to this address:
$ addr2line -e main 0x605
/home/oren/main.cpp:3
And finally, let's see what's on line 3 of our source file [[ drumroll ]]:
$ sed -n "3,3p" /home/oren/main.cpp
int whereIsMyVar = 5;
So as you can see, the name whereIsMyVar
is connected via file name + line
to its original source file location.
Upvotes: 3
Reputation: 31
The variables names are non-existent after the compilation process(Exceptions: global variables in shared libs). The whole idea is to convert your source code to machine instructions.
int a = 5;
Assuming this is your global variable, it will be assigned a address in memory let's say 0xFFFFFFFF, by the compiler and linker & henceforth, all actions done pertaining to this variable (read/write/modify), will be done via accessing that address.
Upvotes: 0
Reputation: 238361
Where are variable names stored in a C++ program?
The variable names are stored in the source code.
The details of the produced program are outside the scope of the language, but typically, the variable names are stored - if they are stored at all - in "debug information".
Upvotes: 3