Is there a way to include an entire text file as a string in a C program at compile-time?
something like:
file.txt:
This is a little text file
main.c:
#include <stdio.h> int main(void) { #blackmagicinclude("file.txt", content) /* equiv: char[] content = "This is\na little\ntext file"; */ printf("%s", content); }
obtaining a little program that prints on stdout "This is a little text file"
At the moment I used an hackish python script, but it's butt-ugly and limited to only one variable name, can you tell me another way to do it?
I reimplemented xxd in python3, fixing all of xxd's annoyances:
unsigned
on the array.Here is the script, filtered by itself, so you can see what it does:
pyxxd.c
Usage (this extracts the script):
You need my
xtr
utility but you can do it with abash script
. This is a script I callbin2inc
. The first parameter is the name of the resultingchar[] variable
. The second parameter is the name of thefile
. The output is Cinclude file
with the file content encoded (in lowercasehex
) as the variable name given. Thechar array
iszero terminated
, and the length of the data is stored in$variableName_length
YOU CAN GET XTR HERE xtr (character eXTRapolator) is GPLV3
You can do this using
objcopy
:Now you have an object file you can link into your executable which contains symbols for the beginning, end, and size of the content from
myfile.txt
.