gpt4 book ai didi

linker - go + cgo 和链接

转载 作者:IT王子 更新时间:2023-10-29 01:26:54 27 4
gpt4 key购买 nike

我想用下面的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 function _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 returned 1 exit status

我做错了什么?

最佳答案

这就是我构建它的方式。请注意 #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
}

关于linker - go + cgo 和链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14842980/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com