bgeyts668
bgeyts668

Reputation: 166

Building Go with C interface to Gtk+

I'm trying to build a Go programm which uses external C code as an interface for Gtk+.

That's the basic Go code I've got (ui.h.go):

package main

//#cgo pkg-config: gtk+-3.0
//#include "ui.h"
import "C"

func CInit() {
    C.Init(nil, 0)
}

func CMain() {
    C.Main()
}

func CShowWindow() {
    C.ShowWindow()
}

func main() {
    CInit()
    CShowWindow()
    CMain()
}

C code is compiled from vala into an object file (ui.o) and a header file (ui.h):

#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

When I try go build ui.h.go I get:

# 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

Which is logical, I haven't provided my object file. But if I specify it in cgo header of ui.h.go like that...

//#cgo LDFLAGS: ui.o
//#cgo pkg-config: gtk+-3.0
//#include "ui.h"
import "C"

I get multiple definition error, as if it's being linked twice.

# 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

How do I link my ui.o file to the Go program correctly? Thank you.

Upvotes: 1

Views: 320

Answers (1)

bgeyts668
bgeyts668

Reputation: 166

Well, I figured out that cgo does link well with static libraries. So I decided to archive my ui.o into libui.a and link it using #cgo LDFLAGS: -L. -lui and it worked correctly.

Upvotes: 2

Related Questions