prevent gcc from removing an unused variable

前端 未结 5 932
不思量自难忘°
不思量自难忘° 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:57

    You are concerned about gcc removing an unused static char[] variable. AFAIK, the compiler is right to do so.

    Other answers provided suggestion to improve that. But you don't want to change the source code of thousands of files.

    Then, you might perhaps change your build (e.g. some Makefile) so that every such source file using your trick (which is slightly wrong, as discussed here...) would not need to be changed. So you might invoke GCC specifically. You want

     static const char _ver[] __attribute__((used));
    

    (this is a declaration, not a definition) to be compiled before anything else. Put the line above in some _declare_ver.h file, and compile with gcc -include _declare_ver.h command (instead of gcc). If using make add

     CFLAGS += -include _declare_ver.h
    

    in your Makefile.

    BTW, that is a dirty trick. You should consider doing something better (following other answers).

提交回复
热议问题