Scripting with C

Kevel
Kevel Blog
Published in
2 min readJan 10, 2017

C rocks, and is super fun to program in, but it’s hard to use for scripting because (among other reasons!) programs need to be compiled before they can be run. Let’s automate that part!

First you need a little script I wrote called mkgo. It compiles, caches, and runs C files in a manner similar to Python.

curl -L -o mkgo http://bit.ly/2ioczmp
chmod a+x mkgo

Next, make a little test program, hello.c:

cat << EOF > hello.c
#include <stdio.h>
int main(int argc, char **argv) {
printf("hello %s!\n", argv[1]);
return 0;
}
EOF

Then we’ll run the “script”:

./mkgo hello.c world
# "hello world!" is printed and there is much rejoicing

mkgo saw that the program wasn't compiled, and compiled it, storing the binary in $HOME/.mkgo/cache. Then it exec'd the compiled program and passed it the worldargument. Subsequent invocations will be snappier, since the cached executable will be used.

SHEBANGS

Instead of running mkgo you can pop a shebang at the top of your C program, and then execute the C file directly.

First you should move mkgo to somewhere on your $PATH, like this:

sudo cp mkgo /usr/local/bin

Then you can make a standalone script like this:

cat << EOF > hello2.c
#!/usr/bin/env mkgo
#include <stdio.h>
int main(int argc, char **argv) {
printf("hello %s!\n", argv[1]);
return 0;
}
EOF
chmod a+x hello2.c
./hello2.c crazytown

FINAL THOUGHTS

I made mkgo originally so I could use C for fun little utilities I keep in my dotfiles, like this one that abbreviates paths for display in my PS1.

I hope you’re able to have some C fun too using this technique. Thanks for reading!

This article was originally published on Adzerk’s blog by Alan Dipert on 12/23/2016.

--

--

Kevel
Kevel Blog

With Kevel’s APIs you can quickly build custom ad platforms for sponsored listings, native ads, and more — so you can drive revenue and take back the Internet.