Last active
June 7, 2023 15:44
-
-
Save jart/5d0934d26b52f38cad36 to your computer and use it in GitHub Desktop.
Run C code in Bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# lolc.sh - run c code in bash | |
# by justine tunney <[email protected]> | |
# licensed mit or apache 2.0 | |
runc() { | |
local bin=$(mktemp -u) | |
gcc -xc -o ${bin} /dev/stdin || return | |
chmod u+x ${bin} | |
${bin} "$@" | |
local rc=$? | |
rm -f ${bin} | |
return ${rc} | |
} | |
c() { | |
local code=$1 | |
shift | |
{ | |
{ | |
for dep in $(grep -Po '\w+(?=\()' <<<"${code}" | sort -u); do | |
man 2 ${dep} 2>/dev/null | grep -Po '#include <.*?>' | |
man 3 ${dep} 2>/dev/null | grep -Po '#include <.*?>' | |
done | |
} | sort -u | |
printf "int main(int argc, char** argv) {\n" | |
printf " %s;\n" "${code}" | |
printf " return 0;\n" | |
printf "}\n" | |
} | runc "$@" | |
} | |
c 'puts("hello kitty")' | |
c 'printf("%s + %s = %d\n", argv[1], argv[2], atoi(argv[1]) + atoi(argv[2]))' 7 11 |
If you emit a shared library you could do a kind of inline-C-for-bash :-).
Glad to hear that @taviso. I just licensed it wtfpl for the sake of legal formality.
You could consider Fabrice Bellard's blazing-fast TinyCC http://bellard.org/tcc/
Also it supports scripting C
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That's a really neat idea. I'll add this to a contrib directory...maybe a more descriptive name though ;)
I'm afk today, I'll commit this tomorrow.