prevent gcc from removing an unused variable

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

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.

From https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html

Demo:

$ 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

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

Leave a Comment