Monday, February 24, 2020

C: Have (more) fun compiling

And here we are:

...
} else {
    // TODO print the --help text
}
...

On ho... where to start... Lets start by making a simple plain text file and write all the things there. Now we have a help.txt.

The easiest solution would be to just read the help.txt file and print it at runtime, but then we need to package the extra help.txt file and also is "slow".

Could we somehow just pasted in? Yes but then we have to add quotes and handle special characters and half of our main.c file will be strings.

xxd. Oh! What is that? If you run:

xxd -i help.txt

We get this very readable c-string

unsigned char help[] = {
  0x63, 0x61, 0x74, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x3a, 0x20, 0x75, 0x6e,
  0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x20, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e,
  0x3a, 0x20, 0x25, 0x63, 0x0a, 0x0a, 0x55, 0x73, 0x61, 0x67, 0x65, 0x3a,
...

Seems good. Does it matter that is so readable, not really its just a build intermediate file. Lets add it to the Makefile with all the other build intermediate files:

help.c:
    xxd -i help > help.c

Now, how about a include in the middle of nowhere:

...
} else {
    #include "help.c"
    printf(help);
}
...

EDIT: xxd does not add a null character at the end...




done_