Order of variables in the stack (GCC) [duplicate]

2019-08-11 23:54发布

问题:

This question already has an answer here:

  • Order of local variable allocation on the stack 9 answers

When compiling C code in GCC, is there any way to guarantee that the stack variables will appear in the stack in the order i declare them (or in reversed order, doesn't matter to me)? I know this is possible via structs but I would rather not use them.

回答1:

The only way would be a struct which includes all variables in the order you like.

For local variables the compiler is free to reorder/reuse variables at any order it suits her. Some variables may not have a memory location at all, they live only in registers, others will be optimized away completely.



回答2:

If you are adamant that you do not want to use a struct then you will have to allocate the stack memory yourself with alloca(). But then you will need to manage your local variables manually within that block of stack memory.

I would not recommend that you do this. Use a struct.



回答3:

The most reliable approach is to direct gcc to produce assembly language output using gcc -S, and examine the assembly language output to find out which variables have been put where. If you compile without optimisations, the variables probably won't get removed or rearranged, and if you assign different values to each local variable it should be easy to spot each one.

I admit that this is not very high-tech. But if you want to be sure that gcc is generating code that works in a particular way, you will have to look at the code it generates...