【发布时间】:2016-06-23 09:32:13
【问题描述】:
如何使用 Golang Generated libgolang.a 从 C 代码构建 C 可执行文件:test.exe:
这些命令在 Ubuntu x86-64 中生成可执行二进制“测试”并且可以正常工作(但在 Windows x86-64 中不行):
go build -buildmode c-archive -o libgolang.a
gcc -o test _main.c libgolang.a -lpthread
与:
这是main.go 文件:
package main
import "C"
import "fmt"
//export Add
func Add(a, b uint64) uint64 {
return a + b
}
func main() {
fmt.Println("Hi")
}
这是_main.c文件:
#include <stdio.h>
#include <stdint.h>
#include "libgolang.h"
int main()
{
uint64_t a=10;
uint64_t b=20;
uint64_t c=Add(a,b);
printf("%ld\n",c);
return 0;
}
在 Windows 中这个命令:
go build -buildmode c-archive -o libgolang.a
工作正常并生成libgolang.a 和libgolang.h 文件。 libgolang.h:
/* Created by "go tool cgo" - DO NOT EDIT. */
/* package github.com/ARamazani/go/DLL */
/* Start of preamble from import "C" comments. */
/* End of preamble from import "C" comments. */
/* Start of boilerplate cgo prologue. */
#ifndef GO_CGO_PROLOGUE_H
#define GO_CGO_PROLOGUE_H
typedef signed char GoInt8;
typedef unsigned char GoUint8;
typedef short GoInt16;
typedef unsigned short GoUint16;
typedef int GoInt32;
typedef unsigned int GoUint32;
typedef long long GoInt64;
typedef unsigned long long GoUint64;
typedef GoInt64 GoInt;
typedef GoUint64 GoUint;
typedef __SIZE_TYPE__ GoUintptr;
typedef float GoFloat32;
typedef double GoFloat64;
typedef float _Complex GoComplex64;
typedef double _Complex GoComplex128;
/*
static assertion to make sure the file is being used on architecture
at least with matching size of GoInt.
*/
typedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*)==64/8 ? 1:-1];
typedef struct { const char *p; GoInt n; } GoString;
typedef void *GoMap;
typedef void *GoChan;
typedef struct { void *t; void *v; } GoInterface;
typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;
#endif
/* End of boilerplate cgo prologue. */
#ifdef __cplusplus
extern "C" {
#endif
extern GoUint64 Add(GoUint64 p0, GoUint64 p1);
#ifdef __cplusplus
}
#endif
但是这个命令:
gcc -o test _main.c libgolang.a -lpthread
输出:
libgolang.a(go.o):(.data+0x2150): undefined reference to `NtWaitForSingleObject'
libgolang.a(go.o):(.data+0x21b8): undefined reference to `WSAGetOverlappedResult'
libgolang.a(go.o):(.data+0x21d8): undefined reference to `timeBeginPeriod'
collect2.exe: error: ld returned 1 exit status
go version go1.7rc3 windows/amd64
我想使用 C 代码中的 libgolang.a 来构建 C 可执行文件:test.exe
有什么解决方法吗?
一些有用的链接:
http://blog.ralch.com/tutorial/golang-sharing-libraries/
Using Go code in an existing C project
Using Go on existing C project
【问题讨论】:
-
这个问题类似于this one。
-
@jean-nicolas-moal:不,不是。
-
好的。您能否向我们提供有关 Windows 上发生的情况(构建或运行时错误)的更多信息?
-
我看到的第一件事是你的 main.c 文件不知道 Go "Add" 函数。您应该在 main.c 中包含 go 生成的标头。而且go 1.7还没有出来,你为什么用它?第二件事,似乎链接器没有找到库(“未定义的引用”错误),但我不知道那些函数(我不是 Windows 用户)希望有人对那些有想法链接器错误。
标签: go