从删除未使用的变量prevent GCC [英] prevent gcc from removing an unused variable

查看:244
本文介绍了从删除未使用的变量prevent GCC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的源文件,我们通常有一个版本字符串这样的:

In our source files we usually have a version string like that:

static const char srcvers[] = "VERSION/foo.c/1.01/09.04.15";

在该字符串不优化掉,它在某些情况下非常有用,因为人们可以通过简单地调用确定链接到可执行的每一个源文件的版本字符串的a.out | grep的版本

When that string isn't optimized away, it's quite useful in certain cases, as one can determine the version of each source file linked to an executable by simply calling strings a.out | grep VERSION.

不幸的是它的按GCC优化掉(使用'-O')。所以我的问题是,是否有一个简单的方法(编译器开关将是巨大的),使海湾合作委员会保持这一变量(它的名字是永远不变的)不关闭任何其他优化。

Unfortunately it is optimized away by gcc (using '-O'). So my question is, is there a simple way (a compiler switch would be great) to make gcc keep that variable (its name is always the same) without switching off any other optimizations.

修改

什么,在我看来,让来自<不同的问题href=\"http://stackoverflow.com/questions/7083482/how-to-$p$pvent-compiler-optimization-on-a-small-piece-of-$c$c\">that 之一,就是我希望能找到我就不会去触碰数千个源文件的解决方案。

What, in my opinion, makes the question different from that one, is that I'm was hoping to find a solution for which I wouldn't have to touch thousands of source files.

推荐答案

您可以使用 __属性__((使用))海湾合作委员会(也适用于铛)特定的(我见这个问题被标记 GCC )属性是:

You can use __attribute__((used)) gcc (also works in clang) specific (I see that the question is tagged gcc) attributes for this:

这个属性附加到一个函数,意味着code必须是发出该函数,即使它看起来该函数没有被引用。这是有用的,例如,当函数仅在内嵌组件被引用。

This attribute, attached to a function, means that code must be emitted for the function even if it appears that the function is not referenced. This is useful, for example, when the function is referenced only in inline assembly.

从<一个href=\"https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html\">https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html

演示:

$ cat a.c
static const char srcvers[] __attribute__((used)) = "VERSION/foo.c/1.01/09.04.15";
$ gcc -O3 -c a.c
$ strings a.o
VERSION/foo.c/1.01/09.04.15

您可以使用一些#如果的#define s到使这个更简洁,也汇编的编译器不支持此扩展名。

You can use some #ifs and #defines to make this terser and also compile on compilers which don't support this extension.

这篇关于从删除未使用的变量prevent GCC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆