objcopy --input binary --output elf64-x86-64 myfile.txt myfile.o extern char foo_start[] asm("section$start$__DATA$__foo");
extern char foo_end[] asm("section$end$__DATA$__foo");Alternatives being : - use objcopy but this needs to specify the binary of the output, which some build settings can make complex at the compile stage - use ld and -o binary. this works but this will put all data in .data section which puts it in ram, without being able to change it. - use incbin on inline assembly. this will work too but it's slightly more complex and relies on inline assembly so a bit less portable. - use xxd utility : this only works on linux, does not export const unsigned char[] (fixable with a simple sed) and we lack the ability to export just a header or control prefix / extensions.
I've needed to do this to embed images in an application written on bare metal before. objcopy and its ilk do turn the data into a byte array that has a symbol in the symbol table. You then reference that symbol in your code. Generally you're not embedding this stuff in an ELF in that case.
The koio utility might better written in POSIX shell.
FWIW, here's a simple POSIX shell-compatible routine that will convert an 8-bit stream into a quoted C string
cstring() {
# use od to translate each byte to hexadecimal, sed to format as
# proper C string
od -An -tx1 -v | sed -ne '/./p' | sed -e '
# prefix \x to each hexadecimal pair and remove trailing space
s/\([0-9a-fA-F][0-9a-fA-F]\)[[:space:]]*/\\x\1/g;
# quote escaped bytes
s/^[[:space:]]*/"/;
s/$/"/;
# escape newline for all but the last line
$!s/$/ \\/;
'
}It is pretty perfect for my project, which is a deep learning application for Android. I use it to embed the CNN model file into the C++ code. It let me avoid putting it in the apk, and then loading it from Java, and then passing it to C++.
One obvious improvement would be to compress the stored data, via gzip/bzip/similar, which would result in a smaller binary. As a small side-effect the embedded resources would be less visible to anybody who ran "strings" against your binary.