使用C接口构建Go到Gtk +

时间:2015-10-25 12:35:46

标签: go compiler-errors linker cgo

我正在尝试构建一个Go程序,它使用外部C代码作为Gtk +的接口。

这是我得到的基本Go代码(ui.h.go):

#ifndef __UI_H__
#define __UI_H__

#include <glib.h>
#include <stdlib.h>
#include <string.h>

G_BEGIN_DECLS

void ShowWindow (void);
void Init (gchar** args, int args_length1);
void Main (void);

G_END_DECLS

#endif

C代码从vala编译成目标文件(ui.o)和头文件(ui.h):

go build ui.h.go

当我尝试# command-line-arguments /tmp/go-build916459533/command-line-arguments/_obj/ui.h.cgo2.o: In function `_cgo_80fc53cbf347_Cfunc_Init': ./ui.h.go:37: undefined reference to `Init' /tmp/go-build916459533/command-line-arguments/_obj/ui.h.cgo2.o: In function `_cgo_80fc53cbf347_Cfunc_Main': ./ui.h.go:46: undefined reference to `Main' /tmp/go-build916459533/command-line-arguments/_obj/ui.h.cgo2.o: In function `_cgo_80fc53cbf347_Cfunc_ShowWindow': ./ui.h.go:55: undefined reference to `ShowWindow' collect2: error: ld returned 1 exit status 时,我得到了:

ui.h.go

哪个是合乎逻辑的,我没有提供我的目标文件。但是,如果我在//#cgo LDFLAGS: ui.o //#cgo pkg-config: gtk+-3.0 //#include "ui.h" import "C" 的cgo标题中指定它...

# command-line-arguments
/usr/local/go/pkg/tool/linux_amd64/link: running gcc failed: exit status 1
ui.o:(.bss+0x0): multiple definition of `window'
/tmp/go-link-461834384/000000.o:/home/oleg/Документы/Projects/rasp/ui.h.go:38: first defined here
ui.o: In function `ShowWindow':
ui.c:(.text+0x0): multiple definition of `ShowWindow'
/tmp/go-link-461834384/000000.o:(.text+0x25): first defined here
ui.o: In function `Init':
ui.c:(.text+0x29): multiple definition of `Init'
/tmp/go-link-461834384/000000.o:(.text+0x4e): first defined here
ui.o: In function `Main':
ui.c:(.text+0x116): multiple definition of `Main'
/tmp/go-link-461834384/000000.o:(.text+0x13b): first defined here
collect2: error: ld returned 1 exit status

我得到多个定义错误,好像它被链接了两次。

<!DOCTYPE html>
<html>
    <head>
        <title>TEST</title>
        <script type="text/javascript">


            function sendToPage(){
                var input = document.getElementById("search").value;
                 //alert(input);
                if (input == "happy"){
                    location.href = "suggestion_happy.html";
                    return false;
                }
                else if (input == "sad"){
                    location.href = "suggestion_sad.html";
                    return false;
                }
                else {
                    alert('Invalid Input.');
                }
                    }
        </script>
    </head>
    <body>
        <div>
                <input type="text" method="put" id="search" placeholder="Search" value="">
                <input type='submit' onclick="sendToPage();" />
        </div>
    </body>
</html>

如何正确地将我的ui.o文件链接到Go程序? 谢谢。

1 个答案:

答案 0 :(得分:2)

好吧,我发现cgo确实与静态库链接得很好。因此,我决定将ui.o归档到libui.a并使用#cgo LDFLAGS: -L. -lui进行关联,并且工作正常。