How can I get the contents of a file at build time into my C++ string?

后端 未结 5 1531
猫巷女王i
猫巷女王i 2021-01-14 00:05

I have a file I am compiling in C++ in which I wish to have a string whose value is the contents of a file at the time of compilation.

In other words, I\'d like to #

5条回答
  •  一个人的身影
    2021-01-14 01:05

    Try to see if your compiler/linker suite has a program called something like bin2obj. If it exists, it will usually take any file and generate a .o or .obj file that you can instruct the linker to link into your program. (How to do this varies by build environment.)

    Typically, then, you'll end up with one or two symbols you can make visible to your code like so:

    extern "C" const char * myFile_start;
    extern "C" unsigned int myFile_size;
    

    The linker will make sure myFile_start points at the start of your file, and myFile_size gives you an indication of the length.

    The symbol names may vary, though: you can use the objdump or nm or dumpbin utilities (again, depending on compiler/linker suite) to investigate the generated .o or .obj to find the symbol names (if they're not already documented in your obj2bin tool documentation).

    Please note that this bloats your executable (usually the .data or .rodata sections or equivalent), which can be a problem on some platforms.

    (If you don't have a bin2obj, you may be able to find one by hunting around on a search engine for "bin2obj" with your compiler/IDE name.)

提交回复
热议问题