使用Go 1.5 buildmode = c-archive与从C链接的net / http.Server

即将发布的Go 1.5版本附带了新的构建模式 ,允许导出Go符号从C代码链接和调用。 我一直在玩它并得到基本的“Hello world”示例,但是现在我正在尝试链接一个启动net/http.Server的Go库并且它失败了。 代码看起来像这样( 它也可以在这里获得 ):

gohttplib.go:

 package main import "C" import "net/http" //export ListenAndServe func ListenAndServe(caddr *C.char) { addr := C.GoString(caddr) http.ListenAndServe(addr, nil) } func main() {} 

实例/ C / main.c中:

 #include  #include "../../gohttplib.h" int main() { ListenAndServe(":8000"); return 0; } 

生成静态链接的对象和标头工作正常:

 $ go build -buildmode=c-archive 

但是编译它是失败的:

 $ gcc -o gohttp-c examples/c/main.c gohttplib.a -lpthread Undefined symbols for architecture x86_64: "_CFArrayGetCount", referenced from: _FetchPEMRoots in gohttplib.a(000003.o) "_CFArrayGetValueAtIndex", referenced from: _FetchPEMRoots in gohttplib.a(000003.o) "_CFDataAppendBytes", referenced from: _FetchPEMRoots in gohttplib.a(000003.o) "_CFDataCreateMutable", referenced from: _FetchPEMRoots in gohttplib.a(000003.o) "_CFDataGetBytePtr", referenced from: _FetchPEMRoots in gohttplib.a(000003.o) __cgo_6dbb806e9976_Cfunc_CFDataGetBytePtr in gohttplib.a(000003.o) (maybe you meant: __cgo_6dbb806e9976_Cfunc_CFDataGetBytePtr) "_CFDataGetLength", referenced from: _FetchPEMRoots in gohttplib.a(000003.o) __cgo_6dbb806e9976_Cfunc_CFDataGetLength in gohttplib.a(000003.o) (maybe you meant: __cgo_6dbb806e9976_Cfunc_CFDataGetLength) "_CFRelease", referenced from: _FetchPEMRoots in gohttplib.a(000003.o) __cgo_6dbb806e9976_Cfunc_CFRelease in gohttplib.a(000003.o) (maybe you meant: __cgo_6dbb806e9976_Cfunc_CFRelease) "_SecKeychainItemExport", referenced from: _FetchPEMRoots in gohttplib.a(000003.o) "_SecTrustCopyAnchorCertificates", referenced from: _FetchPEMRoots in gohttplib.a(000003.o) "_kCFAllocatorDefault", referenced from: _FetchPEMRoots in gohttplib.a(000003.o) ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [example-c] Error 1 

这是在OS X 10.9.5上使用Go github存储库(38e3427)的最新版本。 我知道Go 1.5还没有发布,并且没有保证它正常工作,但我这样做是出于教育目的,我怀疑我错过了什么。

相关版本:

 $ ld -v @(#)PROGRAM:ld PROJECT:ld64-241.9 configured to support archs: armv6 armv7 armv7s arm64 i386 x86_64 x86_64h armv6m armv7m armv7em LTO support using: LLVM version 3.5svn $ gcc --version Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn) Target: x86_64-apple-darwin13.4.0 Thread model: posix 

原来在OSX / darwin上存在这个问题。 要解决它,我们需要将-framework CoreFoundation -framework Security选项添加到gcc链接命令。 最后的命令如下所示:

 $ gcc -o gohttp-c examples/c/main.c gohttplib.a \ -framework CoreFoundation -framework Security -lpthread 

在将来的Go版本中可能会删除此要求。 这里有关于这个问题的更多讨论: https : //github.com/golang/go/issues/11258