prevent gcc from removing an unused variable

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

    As I understand your question, you need to add version string to every object file without touching sources. It can be done using next way.

    Create header file, for example include/version.h:

    #ifndef VERSION_H
    #define VERSION_H
    
    static const char _ver[] __attribute__((used)) = "VERSION/foo.c/1.01/09.04.15";
    
    #endif /* VERSION_H */
    

    Then in your Makefile (or whatever your build system is) add next gcc flag:

    CPPFLAGS += -include include/version.h
    

    Of course it should be passed to gcc, e.g. like this:

    %.o: %.c
        $(CC) $(CFLAGS) $(CPPFLAGS) -o $(*).o -c $(*).c
    

    Now you can observe your _ver string compiled to every object file:

    $ objdump -DS src/main.o | grep _ver
    

    Which will show you something like that:

    Disassembly of section .rodata._ver:
    00000000 <_ver>:
    

提交回复
热议问题