Trouble using scriptedmain in MinGW

半世苍凉 提交于 2019-12-04 15:44:35

I found a solution that works in Windows and in Unix: Simply wrap main() in preprocessor instructions that omits it unless explicit compiler flags are set.

scriptedmain.c:

#include <stdio.h>

int meaning_of_life() {
    return 42;
}

#ifdef SCRIPTEDMAIN

int main() {
    printf("Main: The meaning of life is %d\n", meaning_of_life());

    return 0;
}

#endif

Now main() will be entirely omitted unless you compile with

gcc -o scriptedmain -DSCRIPTEDMAIN scriptedmain.c scriptedmain.h

This code is safe to import into other C code, because the preprocessor will strip out main(), leaving you to code your own main. The best part is that this solution no longer depends on obscure compiler macros, only simple preprocessor instructions. This solution works for C++ as well.

This isn't good practice in C regardless of operating system. Best practice in C for anything complicated enough to be worth separating into library and driver is to put main in a file all by itself.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!