转自:http://www.rainhome.org/c%E4%BB%A3%E7%A0%81%E5%BD%93shell%E8%84%9A%E6%9C%AC%E6%9D%A5%E6%89%A7%E8%A1%8C%EF%BC%9F/


C这种编译型语言要运行必然是需要编译的,但是做点手脚亦可从表明上改变这种认知。下面给出两种把C代码当shell脚本来执行的案例。

1. tcc的脚本模式
tcc是C的编译器,脚本模式会直接编译该代码并运行。


#!/usr/bin/tcc -run
#include<stdio.h>
                     
int main()
{
printf(“hello world.\n”);
return 0;
}

2. shell与C代码共存
脚本语言是解释执行的,充分利用#if条件语句来隔离shell和c编译器,达到可以直接运行的效果。

#if 0
file=`mktemp`
gcc -o $file $0
$file
rm $file
exit
#endif
               
#include<stdio.h>
               
int main()
{
printf("hello world.\n");
return 0;
}