去+ 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:在函数_cgo_c0e279f6f16e_Cfunc_XScreenSaverAllocInfo': ./x11.go:52:

  undefined reference toXScreenSaverAllocInfo中/tmp/go-build076004816/opensource.stdk/lib/tools/_obj/x11.cgo2.o:在函数_cgo_c0e279f6f16e_Cfunc_XScreenSaverQueryInfo': ./x11.go:65:

  undefined reference toXScreenSaverQueryInfo'collect2中:错误:ld返回1退出状态


我究竟做错了什么?


LEATH
浏览 248回答 2
2回答

隔江千里

这就是我如何构建它。注意这#cgo LDFLAGS行可能是您所缺少的。我必须进行其他一些更改才能构建它。它似乎在我的Linux机器上返回了正确的答案!package tools// #cgo LDFLAGS: -lXss -lX11// #include <X11/extensions/scrnsaver.h>import "C"func GetIdleTime() (idleTime uint32) {&nbsp; &nbsp; var info *C.XScreenSaverInfo&nbsp; &nbsp; var display *C.Display&nbsp; &nbsp; info = C.XScreenSaverAllocInfo()&nbsp; &nbsp; display = C.XOpenDisplay(nil)&nbsp; &nbsp; defaultRootWindow := C.XDefaultRootWindow(display)&nbsp; &nbsp; C.XScreenSaverQueryInfo(display, C.Drawable(defaultRootWindow), info)&nbsp; &nbsp; idleTime = uint32(info.idle)&nbsp; &nbsp; return}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go