首页 > 应用开发 > C/C++ > C语言和SH脚本的杂交代码
在网上看到了一个把 C语言和bash杂并起来的例子,这个示子如下所示。在下面这个例子中,我们把脚本用#if 0这个预编译给起来,这样就不会让其编译到C语言中了。
1 #if 0
2 echo "Hello from bash!"
3 exit
4 #endif
5 #include <stdlib.h>
6 #include <stdio.h>
7 int main(int argc, char* argv[]) {
8 puts("Hello from C!");
9 return EXIT_SUCCESS;
10 }
下面,让我看看如果来使用这样的程序:
1 $ sh test.sh.c
2 Hello from bash!
3 $ gcc test.sh.c -o test
4 $ ./test
5 Hello from C!
你甚至还可以做一个自我编译,并自我运行的源代码。如下所示:
1 #if 0
2 file=`mktemp`
3 gcc -o $file $0
4 $file
5 rm $file
6 exit
7 #endif
8 #include <stdlib.h>
9 #include <stdio.h>
10
11 int main(int argc, char *argv[]) {
12 puts("Hello from C!");
13 return EXIT_SUCCESS;
14 }
运行:
1 $ sh test.sh.c
2 Hello from C!
3
$
当然,我并不建议你在真正的开发环境中这样使用,我只不过是在介绍一个比较有趣的用法,仅此而已!
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31365439/viewspace-2679794/ ,如需转载,请注明出处,否则将追究法律责任。