Search code examples
linkerbinutilsobject-filessymbol-tableobjcopy

How to specify symbol name when creating objects from raw binary files using objcopy?


As described in this answer, GNU objcopy can be used to create object files from arbitrary file content. This method can be used to embed resources into programs. However, the symbol name is generated by input file name.

For example, if you run:

objcopy --input binary --output elf64-x86-64 --binary-architecture i386:x86-64 myfile.txt myfile.o

The generated object file would contain _binary_myfile_txt_start, _binary_myfile_txt_end and _binary_myfile_txt_size, which simply replaces non-alphanumeric characters with _.

However, when I process files foo.bar and foo_bar, or even multiple foo.bar on different directories, the symbols would be same. So is there a way to manually specify the symbol in output object file to avoid conflict?


Solution

  • I find that I can run objcopy to rename the symbol via --redefine-sym option. The only caveat is I have to run objcopy twice for each input file, once for creating the object file and once for rename symbols.

    The --redefine-sym option can be specified multiple times, so the rename only needs to run objcopy once for all three xxx_start x_end and xxx_size symbols. The input file and output file to objcopy can be same, so you don't need to decide where to place another temp file.