You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用GCC正确编译调用netapi32的代码?编译报错排查

编译NetUserEnum示例代码时遇到的链接与类型冲突问题

环境信息

  • Win10系统
  • 带ucrt64的msys64(x86_64-w64-mingw32)
  • netapi32.dll路径:c:\windows\servicing\LCU\Package_for_RollupFix~31bf3856ad364e35~amd64~~19041.2486.1.5\amd64_microsoft-windows-netapi32_31bf3856ad364e35_10.0.19041.2130_none_0202483cb6bb2fc6\f\netapi32.dll
  • IDE为Atom(未安装Visual Studio)
  • 使用cmd作为控制台

编译过程与错误

执行编译命令:

gcc main.c -o main.exe -lnetapi32

返回错误:

undefined reference to `WinMain' collect2.exe: error: ld returned 1 exit status

将原代码的wMain改为WinMain后,再次编译出现类型冲突错误:

main.c:11:5: error: conflicting types for 'WinMain'; have 'int(int,  wchar_t **)' {aka 'int(int,  short unsigned int **)'}
   11 | int WinMain(int argc, wchar_t *argv[])
      |     ^~~~~~~
In file included from c:/msys64/ucrt64/include/windows.h:70,
                 from main.c:8:
c:/msys64/ucrt64/include/winbase.h:1128:14: note: previous declaration of 'WinMain' with type 'int(struct HINSTANCE__ *, struct HINSTANCE__ *, CHAR *, int)' {aka 'int(struct HINSTANCE__ *, struct HINSTANCE__ *, char *, int)'}
 1128 |   int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd);

问题原因与解决方法

1. 未定义WinMain的原因

MinGW默认将程序视为Windows GUI程序,会寻找WinMain作为入口点,但你的代码是控制台程序,入口为wmain或main。只需在编译时添加-mconsole参数,告知编译器这是控制台程序,即可自动识别原入口函数。

2. WinMain类型冲突的原因

Windows系统对WinMain有固定的参数签名,必须为:

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd);

你自定义的WinMain(int argc, wchar_t *argv[])与系统定义的签名完全不符,因此触发类型冲突错误。

正确编译命令

无需修改原代码的入口函数名,直接使用以下命令编译:

gcc main.c -o main.exe -lnetapi32 -mconsole

内容的提问来源于stack exchange,提问作者Archy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 11:00:42