質問

I am trying to use XLib within Go using this code:

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());
}

I'm compiling this via:

go tool cgo $(FILE)

But it results in the following error messages:

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)

Any idea how to solve this?

役に立ちましたか?

解決

cgo is picky about the formatting: you need to keep the "C" import separate, and place the preamble comments immediately above:

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));
}

他のヒント

First of all, you do not want to use go tool cgo directly, unless you have specific reasons for doing so. Continue to use go build like you would for projects that do not use cgo.

Second, your cgo parameters need to be attached directly to the "C" import, so it has to read

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

import (
  // your other imports
)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top