Skip to content

Instantly share code, notes, and snippets.

@jart
Last active June 7, 2023 15:44
Show Gist options
  • Save jart/5d0934d26b52f38cad36 to your computer and use it in GitHub Desktop.
Save jart/5d0934d26b52f38cad36 to your computer and use it in GitHub Desktop.
Run C code in Bash
#!/bin/bash
# lolc.sh - run c code in bash
# by justine tunney <jtunney@gmail.com>
# 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
@jart
Copy link
Author

jart commented Jul 31, 2015

Glad to hear that @taviso. I just licensed it wtfpl for the sake of legal formality.

@Ismas
Copy link

Ismas commented Aug 2, 2015

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