C in sh

I am currently reading the best book about the C language since the K&R. It's called 21st Century C, was written by Ben Klemens and published by O'Reilly.

There is one gem per page in this book. From big-picture tips to nice little hacks. My favority so far can be found on page 29. It explains how one can embed a small C proram into a shell script.

In a nutshell, this is how you do it:

#!/bin/sh

gcc -xc - << END_OF_C_SECTION
#include <stdio.h>
int main() {
   printf("C inside a shell script!n");
}
END_OF_C_SECTION
./a.out

‘-xc’ indicates to cc that what follows in C code. Also notice the dash ('-') that tells gcc to accept standard input instead of a file.

In a footnote, Klemens points to a complete implementation of this idea by RhysU, who has put his work on github.

Avatar
Lydéric Landry
écrivain et éditeur

Après plusieurs vies, j'écris maintenant