c - gcc 在更改变量声明顺序后保留内存分配

标签 c gcc

<分区>

我有这种形式的功能:

void authenticate()
{
    int auth_flag;
    char password[16];
    ...
}

当我调试程序时,我可以看到 auth_flag 变量在堆栈中的 password 变量之后(这看起来很正常)。

现在当我改变变量声明的顺序时:

void authenticate()
{
    char password[16];
    int auth_flag;
    ...
}

我看到变量 auth_flag 仍然分配在堆栈中的 password 变量之后。

我正在寻找的是避免/控制这种情况的任何方法,无论是使用编译选项还是代码内编译器指令。

最佳答案

根据 GCC documentation "Common Function Attributes" :

  • no_reorder

Do not reorder functions or variables marked no_reorder against each other or top level assembler statements the executable. The actual order in the program will depend on the linker command line. Static variables marked like this are also not removed. This has a similar effect as the -fno-toplevel-reorder option, but only applies to the marked symbols.

并且在 "Optimize Options" :

  • -fno-toplevel-reorder

Do not reorder top-level functions, variables, and asm statements. Output them in the same order that they appear in the input file. When this option is used, unreferenced static variables are not removed. This option is intended to support existing code that relies on a particular ordering. For new code, it is better to use attributes when possible.

关于c - gcc 在更改变量声明顺序后保留内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40080914/

相关文章:

python - 使用 ctypes 将结构从 C 传递到 Python

c - for 循环比较中什么更快?

gcc - GCC为x86生成的 “push %ebp; movl %esp, %ebp”有什么用途?

c++ - 使用线程的 vector 和没有加速

c++ - 避免 typedef C++ 中的声明冲突错误

c - 为什么在 BST 中搜索比二进制搜索算法更快

c++ - MPI_Send/Recv C++ std::string 段错误

c - 我如何修改线程以打印 "hello world again"?在C中

我可以强制 cmake 在特定目标中包含我的头文件吗?

使用 makefile 编译 header 依赖项