Difference between using objcopy and xxding the file into a c source

410 views Asked by At

Say I want to embed a file called data in my C executable.

The result which comes up from google is this linuxjournal page which says use objdump like this

objcopy --input binary \
        --output elf32-i386 \
        --binary-architecture i386 data data.o

However this is dependent on the architecture of the computer, for example when compiling the object from the previous command it gives i386 architecture of input file 'data.o' is incompatible with i386:x86-64 output and I have to change the arguments.

However with the unix tool xxd, I can simply make a c source code with the data in a unsigned char array and an integer with its length and obtain the same result with device independent compilation commands.

data.o: data.c
        gcc -c data.c
data.c: data
        xxd -i data > data.c

What is the preferred method and why?

1

There are 1 answers

0
Dummy00001 On BEST ANSWER

The xxd is not a standard UNIX tool. It is actually part of VIM and is used for implementing its hex editor function. VIM is an optional tool and is not universally available.

The GNU objcopy, on the other hand, is part of GNU binutils and generally is preinstalled on all GNU systems.

In general, when one needs to include a binary file into a program, something simple (as you do with xxd) is preferred over the objcopy. Mainly, for the simple reason that objcopy is heavily under-documented and leaves impression of being an unpolished front-end to the BFD, the underlying library of the binutils. Another reason is that along with the .c file, you can also create the .h file, and make the generated files an integral part of your project.

The article you link already contains a number of examples how to accomplish that. Probably the most popular tool for the purpose is the hexdump, preinstalled on literally all systems. For example, from the top of my head:

# .c
echo 'char data[] = {' > data.c
hexdump -v  -e '1/1  "0x%02X,"' < data.bin >> data.c
echo >> data.c
echo '};' >> data.c
echo 'size_t data_size = sizeof(data);'
# .h
echo 'extern char data[];' > data.h
echo 'extern size_t data_size;' >> data.h