去+ cgo和链接

时间:2013-02-12 22:24:06

标签: linker go cgo

我想使用以下c作为Go的cgo:

#include <X11/extensions/scrnsaver.h>

main() {
  XScreenSaverInfo *info = XScreenSaverAllocInfo();
  Display *display = XOpenDisplay(0);

  XScreenSaverQueryInfo(display, DefaultRootWindow(display), info);
  printf("%u ms\n", info->idle);
}

构建:

gcc -o idle printXIdleTime.c -lX11 -lXss

我为Go的cgo重写了这段代码:

package tools

// #cgo pkg-config: x11
// #include <X11/extensions/scrnsaver.h>
import "C"

func GetIdleTime() (idleTime uint32) {
    var info *C.XScreenSaverInfo
    var display *C.Display 

    info = C.XScreenSaverAllocInfo()
    display = C.XOpenDisplay(0)

    defaultRootWindow := C.XDefaultRootWindow(display)

    C.XScreenSaverQueryInfo(display, defaultRootWindow, info)
    idleTime = info.idle

    return
}

尝试编译:

go build -gccgoflags="-lXss -lX11"

然而我收到链接器错误:

  

/tmp/go-build076004816/opensource.stdk/lib/tools/_obj/x11.cgo2.o:In   函数_cgo_c0e279f6f16e_Cfunc_XScreenSaverAllocInfo': ./x11.go:52: undefined reference to XScreenSaverAllocInfo'   /tmp/go-build076004816/opensource.stdk/lib/tools/_obj/x11.cgo2.o:In   function _cgo_c0e279f6f16e_Cfunc_XScreenSaverQueryInfo': ./x11.go:65: undefined reference to XScreenSaverQueryInfo'collect2:error:ld   返回1退出状态

我做错了什么?

2 个答案:

答案 0 :(得分:4)

这就是我如何构建它。请注意#cgo LDFLAGS行,这可能是您所缺少的。我不得不做一些其他的改动来使它构建。它似乎正在我的Linux机器上返回正确的答案!

package tools

// #cgo LDFLAGS: -lXss -lX11
// #include <X11/extensions/scrnsaver.h>
import "C"

func GetIdleTime() (idleTime uint32) {
    var info *C.XScreenSaverInfo
    var display *C.Display

    info = C.XScreenSaverAllocInfo()
    display = C.XOpenDisplay(nil)

    defaultRootWindow := C.XDefaultRootWindow(display)

    C.XScreenSaverQueryInfo(display, C.Drawable(defaultRootWindow), info)
    idleTime = uint32(info.idle)

    return
}

答案 1 :(得分:2)

请注意,这可以使用原生X Go Binding和ScreenSaver扩展程序来完成:

package main

import (
    "fmt"
    "log"

    "github.com/BurntSushi/xgb"
    "github.com/BurntSushi/xgb/xproto"
    "github.com/BurntSushi/xgb/screensaver"
)

func main() {
    X, err := xgb.NewConn()
    if err != nil {
        log.Fatal(err)
    }

    if err = screensaver.Init(X); err != nil {
        log.Fatal(err)
    }

    root := xproto.Setup(X).DefaultScreen(X).Root
    info, err := screensaver.QueryInfo(X, xproto.Drawable(root)).Reply()
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Idle: %d\n", info.MsSinceUserInput)
}

输出:

[andrew@Liger go] go run xscreensaver_idle.go 
Idle: 1040