在我们的源文件中,我们通常有一个类似的版本字符串:
static const char srcvers[] = "VERSION/foo.c/1.01/09.04.15";
Run Code Online (Sandbox Code Playgroud)
当该字符串未被优化时,它在某些情况下非常有用,因为可以通过简单地调用来确定链接到可执行文件的每个源文件的版本strings a.out | grep VERSION.
不幸的是,它被 gcc优化(使用'-O').所以我的问题是,是否有一种简单的方法(编译器开关会很棒)使gcc保持该变量(其名称始终相同)而不关闭任何其他优化.
编辑
在我看来,这个问题与那个不同的是,我希望找到一个解决方案,我不必触及成千上万的源文件.
我有这个C文件(sample.c):
#include <stdio.h>
#define M 42
#define ADD(x) (M + x)
int main ()
{
printf("%d\n", M);
printf("%d\n", ADD(2));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我编译的是:
$ gcc -O0 -Wall -g3 sample.c -o sample
Run Code Online (Sandbox Code Playgroud)
然后调试
$ gdb ./sample
GNU gdb (Gentoo 7.3.1 p2) 7.3.1
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type …Run Code Online (Sandbox Code Playgroud)