Go 1.5 の今後のリリースには、Go シンボルをエクスポートしてリンクし、C コードから呼び出すことができる新しいビルドモードが付属しています。私はそれをいじっていて、基本的な「Hello world」の例が機能するようになりましたが、今、開始する Go ライブラリをリンクしようとしていますが、net/http.Server
失敗しています。コードは次のようになります (こちらからも入手できます)。
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 <stdio.h>
#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