问题描述
我想重现,捆绑API和CLI在相同的C源$ C $ C文件()。这是用Python完成与如果__name __ ==__ main__:主()
并在gcc / Unix下,这看起来像:
I want to reproduce this Perl code in C, bundling API and CLI in the same C source code file (scriptedmain). This is done in Python with if __name__=="__main__": main()
and in gcc/Unix, this looks like:
$ gcc -o scriptedmain scriptedmain.c scriptedmain.h
$ ./scriptedmain
Main: The meaning of life is 42
$ gcc -o test test.c scriptedmain.c scriptedmain.h
$ ./test
Test: The meaning of life is 42
scriptedmain.h
scriptedmain.h
int meaning_of_life();
scriptedmain.c
scriptedmain.c
#include <stdio.h>
int meaning_of_life() {
return 42;
}
int __attribute__((weak)) main() {
printf("Main: The meaning of life is %d\n", meaning_of_life());
return 0;
}
test.c的
test.c
#include "scriptedmain.h"
#include <stdio.h>
extern int meaning_of_life();
int main() {
printf("Test: The meaning of life is %d\n", meaning_of_life());
return 0;
}
然而,当我尝试用gcc /草莓编译,我得到:
However, when I try to compile with gcc/Strawberry, I get:
C:\>gcc -o scriptedmain scriptedmain.c scriptedmain.h
c:/strawberry/c/bin/../lib/gcc/i686-w64-mingw32/4.4.3/../../../../i686-w64-mingw32/lib/libmingw32.a(lib32_libmingw32_a-crt0_c.o): In function `main':
/opt/W64_156151-src.32/build-crt/../mingw-w64-crt/crt/crt0_c.c:18: undefined reference to `WinMain@16'
collect2: ld returned 1 exit status
当我尝试用gcc / MinGW的编译,我得到:
And when I try to compile with gcc/MinGW, I get:
$ gcc -o scriptedmain -mwindows scriptedmain.c scriptedmain.h
c:/mingw/bin/../lib/gcc/mingw32/4.5.2/../../../libmingw32.a(main.o):main.c:(.text+0x104): undefined reference to `WinMain@16'
collect2: ld returned 1 exit status
我怎样才能获得GCC在Windows中识别 __ __属性((弱))
语法?
此外,G ++显示了同样的错误。
Also, G++ shows the same error.
推荐答案
我发现,在Windows和Unix的有效的解决方案:简单包装的main()
$ p中$ pprocessor指令忽略它,除非明确的编译器设置标志。
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:
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
现在的main()
将被完全忽略,除非你用
Now main()
will be entirely omitted unless you compile with
gcc -o scriptedmain -DSCRIPTEDMAIN scriptedmain.c scriptedmain.h
这code是安全的导入到其他C code,因为preprocessor将去掉的main()
,更让您code本的主力。最好的部分是,这种解决方案不再依赖于晦涩的编译器的宏,只有简单的preprocessor说明。该解决方案适用于为好。
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.
这篇关于在MinGW的使用scriptedmain麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!