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

如何在Microsoft Visual Studio C++中调用Go代码?

能否在Microsoft Visual Studio C++中调用Go代码?

目前来看,cgo仅能通过MinGW GCC编译,这导致在Visual Studio C++中调用Go代码陷入两难困境:

  • 若将MinGW编译生成的.a库与常规Visual C++代码链接,会因符号不兼容失败,错误示例如下:
clang -w *.cpp v2pn.a
LINK : warning LNK4217: symbol '__acrt_iob_func' defined in 'libucrt.lib(_file.obj)' is imported by 'v2pn.a(000005.o)' in function '_cgo_preinit_init'
LINK : warning LNK4286: symbol '__acrt_iob_func' defined in 'libucrt.lib(_file.obj)' is imported by 'v2pn.a(000006.o)'
LINK : warning LNK4217: symbol '_errno' defined in 'libucrt.lib(errno.obj)' is imported by 'v2pn.a(000005.o)' in function '_cgo_beginthread'
v2pn.a(000005.o) : error LNK2019: unresolved external symbol __imp__beginthread referenced in function '_cgo_beginthread'
v2pn.a(000005.o) : error LNK2019: unresolved external symbol __mingw_vfprintf referenced in function 'fprintf'
v2pn.a(000006.o) : error LNK2001: unresolved external symbol __mingw_vfprintf
a.exe : fatal error LNK1120: 2 unresolved externals
clang: error: linker command failed with exit code 1120 (use -v to see invocation)
  • 若用MinGW GCC将.a库与Visual C++代码链接,则会因MinGW头文件与Windows SDK不同步,出现大量编译错误。例如调用SetInterfaceDnsSettings相关代码时:
gcc.exe *.cpp v2pn.a
v2pn.cpp: In function 'void set_dns_by_guid(PCHAR)':
v2pn.cpp:48:5: error: 'DNS_INTERFACE_SETTINGS' was not declared in this scope
   48 |     DNS_INTERFACE_SETTINGS settings = {DNS_INTERFACE_SETTINGS_VERSION1};
      |     ^~~~~~~~~~~~~~~~~~~~~~
v2pn.cpp:49:5: error: 'settings' was not declared in this scope
   49 |     settings.Flags = 0x0002;
      |     ^~~~~~~~
v2pn.cpp:51:17: error: 'SetInterfaceDnsSettings' was not declared in this scope
   51 |     DWORD ret = SetInterfaceDnsSettings(interfaceGUID, &settings);
      |                 ^~~~~~~~~~~~~~~~~~~~~~~

原因在于Windows SDK的netioapi.h包含DNS_INTERFACE_SETTINGS的声明,但MinGW的同名头文件中没有该定义。

目前能找到的方案均基于MinGW GCC编译cgo,但这种方式无法兼容Visual Studio C++的完整开发环境,总会出现部分代码无法正常运行的问题,该问题暂时没有可行的解决办法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 00:45:33