【问题标题】:Linking Golang with XLib将 Golang 与 XLib 连接起来
【发布时间】:2013-08-15 01:14:02
【问题描述】:

我正在尝试使用以下代码在 Go 中使用 XLib:

package main

// #cgo LDFLAGS: -lX11
// #include <X11/Xlib.h>
import (
    "C"
    "fmt"
)

func main() {
    var dpy = C.XOpenDisplay(nil);
    if dpy == nil {
        panic("Can't open display")
    }

    fmt.Println("%ix%i", C.XDisplayWidth(), C.XDisplayHeight());
}

我正在通过以下方式编译:

go tool cgo $(FILE)

但它会导致以下错误消息:

1: error: 'XOpenDisplay' undeclared (first use in this function)
1: note: each undeclared identifier is reported only once for each function it appears in
1: error: 'XDisplayWidth' undeclared (first use in this function)
1: error: 'XDisplayHeight' undeclared (first use in this function)

知道如何解决这个问题吗?

【问题讨论】:

    标签: go cgo


    【解决方案1】:

    cgo 对格式很挑剔:您需要将“C”导入分开,并将序言 cmets 直接放在上方:

    package main
    
    // #cgo LDFLAGS: -lX11
    // #include <X11/Xlib.h>
    import "C"
    
    import (
        "fmt"
    )
    
    func main() {
    
        var dpy = C.XOpenDisplay(nil)
        if dpy == nil {
            panic("Can't open display")
        }
    
        fmt.Println("%ix%i", C.XDisplayWidth(dpy, 0), C.XDisplayHeight(dpy, 0));
    }
    

    【讨论】:

      【解决方案2】:

      首先,您不想直接使用go tool cgo,除非您有特定的理由这样做。继续使用go build,就像在不使用 cgo 的项目中一样。

      其次,你的cgo参数需要直接附加到“C”导入,所以必须读取

      // #cgo LDFLAGS: -lX11
      // #include <X11/Xlib.h>
      import "C"
      
      import (
        // your other imports
      )
      

      【讨论】:

        猜你喜欢
        • 2018-01-25
        • 2017-09-24
        • 2014-08-16
        • 2023-03-29
        • 2020-01-20
        • 2012-03-10
        • 2022-01-19
        • 2013-01-27
        • 2020-10-10
        相关资源
        最近更新 更多