prevent gcc from removing an unused variable

前端 未结 5 936
不思量自难忘°
不思量自难忘° 2020-12-16 12:27

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

static const char srcvers[] = \"VERSION/foo.c/1.01/09.0         


        
5条回答
  •  一生所求
    2020-12-16 12:41

    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.

提交回复
热议问题