您的代码没有副作用:它不会通过网络发送任何内容,也不会写入文件,因此 gcc 忽略了该代码。现代 gcc 版本有 -fdump-* 选项,允许记录编译器的每个阶段:
$ gcc -O2 -fdump-tree-all elide.c
之后gcc会生成一堆输出文件:
$ ls -1 | head
a.out
elide.c
elide.c.001t.tu
elide.c.003t.original
elide.c.004t.gimple
elide.c.007t.omplower
...
比较它们可能会揭示代码被删除的阶段。在我的情况下(GCC 4.8.1),它是cddce 阶段。来自 GCC 源文件gcc/tree-ssa-dce.c:
/* Dead code elimination.
References:
Building an Optimizing Compiler,
Robert Morgan, Butterworth-Heinemann, 1998, Section 8.9.
Advanced Compiler Design and Implementation,
Steven Muchnick, Morgan Kaufmann, 1997, Section 18.10.
Dead-code elimination is the removal of statements which have no
impact on the program's output. "Dead statements" have no impact
on the program's output, while "necessary statements" may have
impact on the output.
The algorithm consists of three phases:
1. Marking as necessary all statements known to be necessary,
e.g. most function calls, writing a value to memory, etc;
2. Propagating necessary statements, e.g., the statements
giving values to operands in necessary statements; and
3. Removing dead statements. */
您可以通过将变量标记为volatile 来显式破坏优化器:
volatile int i,j,k;
volatile int var;
volatile int big_num = 1000000;
volatile int x[1];
volatile 会告诉编译器,写入内存单元有副作用