利用 C 前置處理器的 #if 0 區塊,可以將 Shell 腳本隱藏在 C 原始碼中,使同一檔案既能直接用 sh 執行,又能經 gcc 編譯執行。這是一種有趣的「多語言共存」技巧,雖不建議用於正式專案,但能加深對編譯流程與腳本解析的理解。
#if 0
echo "Hello from bash!"
exit
#endif
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
puts("Hello from C!");
return EXIT_SUCCESS;
}
$ sh test.sh.c
Hello from bash!
$ gcc test.sh.c -o test
$ ./test
Hello from C!
#if 0
file=$(mktemp)
gcc -o "$file" "$0"
"$file"
rm "$file"
exit
#endif
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
puts("Hello from C!");
return EXIT_SUCCESS;
}
直接 sh test.sh.c 即可完成編譯、執行、清理暫存檔。
#if 0 只是註解,依序執行 echo/exit 或編譯指令。#if 0 ... #endif 區塊被預處理器移除,僅見合法 C 碼。#if 0 行為,跨編譯器/平台可能有差異。同理可構思「Python + C」、「JavaScript + C」等混合檔,核心在於利用各語言的註解/預處理機制互相隱藏對方的程式碼區塊。