4

I need to embed some data into an executable or SO file on Linux. I've found I can do it with ld --format binary, however, all examples I've seen assume the data file is in the current directory. If it is not, then the resulting symbol name gets complicated, as it tries to include the full path to the file.

Is there a way to provide a name for the symbol explicitly, for ex. Say symbol name for this data should be MyData ?

Thanks

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
  • You can read up on the options accepted by the linker: `man ld`. I'm not sure, but `-soname` might be the one you're looking for. – n.st Oct 03 '13 at 21:50

1 Answers1

6

You definitely can not specify linker-generated binary symbol name in --format=binary approach. But with -L option you may specify path to binary and linker will see it in any path without specifying path in filename, leaving symbol name short and pretty.

But lets talk about custom symbol names more. You can do it with little inline assembler magic (incbin directive). Prepare assembler file like:

    .section .rodata
    .global MyData
    .type   MyData, @object
    .align  4
MyData:
    .incbin "longpath/to/my/binary/MyData.bin"
    .global MyData_size
    .type   MyData_size, @object
    .align  4
MyData_size:
    .int    MyData_size - MyData

And link it together with you C code, safely using:

extern char MyData[];
extern unsigned MyData_size;

Also (as with linker approach, listed above) you may use simple form:

    .incbin "MyData.bin"

And specify -Ilongpath/to/my/binary/ as GCC option.

Konstantin Vladimirov
  • 6,791
  • 1
  • 27
  • 36
  • You may mark it as correct (check button at the left side of answer), if it fits your question. This will generally help others to find it among answered ones. – Konstantin Vladimirov Oct 11 '13 at 07:40
  • 1
    It would be nice to expand on how to control the linker's search path. `-L` does not appear to work as that is for searching libraries to link with `-lfoo`, not input files... – Thomas Oct 29 '14 at 01:44
  • Also mentioned at: https://stackoverflow.com/questions/4158900/embedding-resources-in-executable-using-gcc/36295692#36295692 – Ciro Santilli OurBigBook.com Nov 16 '18 at 17:20