Embedding resources in executable using GCC

前端 未结 4 1706
小鲜肉
小鲜肉 2020-11-22 16:21

I\'m looking for a way to easily embed any external binary data in a C/C++ application compiled by GCC.

A good example of what I\'d like to do is handling shader cod

4条回答
  •  野性不改
    2020-11-22 16:52

    The .incbin GAS directive can be used for this task. Here is a totally free licenced library that wraps around it:

    https://github.com/graphitemaster/incbin

    To recap. The incbin method is like this. You have a thing.s assembly file that you compile with gcc -c thing.s

          .section .rodata
        .global thing
        .type   thing, @object
        .align  4
    thing:
        .incbin "meh.bin"
    thing_end:
        .global thing_size
        .type   thing_size, @object
        .align  4
    thing_size:
        .int    thing_end - thing
    

    In your c or cpp code you can reference it with:

    extern const char thing[];
    extern const char* thing_end;
    extern int thing_size;
    

    So then you link the resulting .o with the rest of the compilation units. Credit where due is to @John Ripley with his answer here: C/C++ with GCC: Statically add resource files to executable/library

    But the above is not as convenient as what incbin can give you. To accomplish the above with incbin you don't need to write any assembler. Just the following will do:

    #include "incbin.h"
    
    INCBIN(thing, "meh.bin");
    
    int main(int argc, char* argv[])
    {
        // Now use thing
        printf("thing=%p\n", gThingData);
        printf("thing len=%d\n", gThingSize);   
    }
    

提交回复
热议问题