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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s