Convert Binary File into Object File for C/C++

Irony Superman
1 min readApr 3, 2019

--

Sometimes we need to embed a binary file into library/executable file. One possible method is to use command “xxd -i binary.dat >> binary_dat.cpp” to generate a cpp file and compile it. However, if this binary file is very large, it is very very painful to compile the generated cpp file.

The following is the method to convert binary file into object file for c/c++ without compilation.

# The following command will generate object file with symbols "_binary_{FILE_PATH}_{start/end/size}" (./ => __) 
ld -r -b binary ./MODEL.mdl -o ../mdl/mdl.o

# The following command will change data memory from writable to read-only (this step is optional)
objcopy --rename-section .data=.rodata ../mdl/mdl.o

# Set symbols to hidden
../elf_tools/rebind --visibility=hidden ../mdl/mdl.o _binary___MODEL_mdl_start
../elf_tools/rebind --visibility=hidden ../mdl/mdl.o _binary___MODEL_mdl_end
../elf_tools/rebind --visibility=hidden ../mdl/mdl.o _binary___MODEL_mdl_size
# Verifying symbols are hidden
objdump -x ../mdl/mdl.o | grep binary

Reference

Embedding binary data in executables:
https://csl.name/post/embedding-binary-data/
https://stackoverflow.com/questions/47414607/how-to-include-data-object-files-images-etc-in-program-and-access-the-symbol

Set symbol visibility to hidden by using ELFkickers/rebind:
https://github.com/BR903/ELFkickers/tree/master/rebind

Code

extern const uint8_t _binary___MODEL_mdl_start[]; 
extern const uint8_t _binary___MODEL_mdl_end[];
const uint8_t* MODEL_MDL_start = _binary___MODEL_mdl_start;
const uint8_t* MODEL_MDL_end = _binary___MODEL_mdl_end;

size_t mdl_size = (size_t) (MODEL_MDL_end - MODEL_MDL_start);

//Note: do NOT use this "_binary___MODEL_mdl_size"

--

--