在 c 代码文件插入 shell 命令

今天看到一个帖子:Just realized you can put shell script inside c source files,想到以前有个朋友也是这么使用 c,觉得挺神奇的。

这个是在 c 源代码文件,使用 macro 宏定义一组 shell 命令,然后再退出 shell,这样就不会在继续执行真正的 c 代码了。这样做的好处是可以使用一个命令 sh main.c 即可快速运行可执行文件,对于一些简单部署的任务比较方便。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#if 0
cc -o /tmp/app main.c
/tmp/app
exit # required, otherwise sh will try to interpret the C code below
#endif

#include <stdio.h>

int main(void)
{
    printf("quick script\n");
    return 0;
}
1
2
3
sh main.c

quick script

This is called a Polyglot and it’s possible to get more than just 2 languages in one file

Polyglot

在这个帖子的回复评论里,可以找到其他实际的工程使用例子:

相关内容

william 支付宝支付宝
william 微信微信
0%