Skip to content

Instantly share code, notes, and snippets.

@cslarsen
Created January 29, 2014 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cslarsen/8686161 to your computer and use it in GitHub Desktop.
Save cslarsen/8686161 to your computer and use it in GitHub Desktop.
How to embed binary objects in your executable.

Shows how to embed binary objects directly in your executable by the linker.

The alternative would be to parse the file and put it in a C-array, which I think is inelegant.

Useful when you want to embed stuff like graphics, media files and so on in your executable.

To run, just type make.

#include <stdio.h>
/*
* To get the name of the foo.o char section, use `objdump -x foo.o`.
*/
extern char _binary_foo_txt_start[];
int main()
{
char *p = _binary_foo_txt_start;
printf("first 10 chars of foo.txt: '%.10s'\n", p);
return 0;
}
This is sentence one. This is sentence two.
This is the third and final sentence.
TARGETS = a.o foo.o a
run: a
./a
all: $(TARGETS)
foo.o: foo.txt
ld -r -b binary -o $@ $<
a: foo.o a.o
clean:
rm -f $(TARGETS)
@cslarsen
Copy link
Author

Output:

$ make
cc    -c -o a.o a.c
ld -r -b binary -o foo.o foo.txt
cc   a.o foo.o   -o a
./a
first 10 chars of foo.txt: 'This is se'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment