1

I am trying to write a go program in windows by importing a dynamic link library that I built. In order to build the go program using these custom .dll files, I am using cgo's CFLAGS and LDFLAGS in go source file. The code looks like this:

/*
#cgo CFLAGS: -I${SRCDIR}/lib
#cgo LDFLAGS: -L${SRCDIR}/lib -lkeyboard
#include <keyboard.h>
*/
import "C"
import "fmt"

func main() {
    fmt.Printf("Hello word\n")
    C.InitKeyboard()

    fmt.Printf("\nEnter: ")

    for {
        r := C.GetCharacter()

        fmt.Printf("%c", r)

        if r == 'q' {
            break
        }
    }

    C.Closeboard()
}

My directory structure:

src
|_hello.go
|_lib
----|_keyboard.h
----|_keyboard.c
----|_libkeyboard.dll

The header (.h) and dynamic link library (.dll) are kept in a folder called 'lib' which is present in the same level as .go program file, this code compiles/builds but when I run the built .exe file it throws an error 'libkeyboard.dll not found', but works when I place the libkeyboard.dll is the same location as the compiled .exe file. I want to understand why is it able to fetch the library file from the mentioned path (./lib) during compile time but failing to do the same during runtime. I know creating PATH variable will help it to locate but why does it not work without setting PATH when I've already given the library files location CFLAGS and LDFLAGS.

And how do I make it work for static library file 'libkeyboard.a' because as I observe the built .exe file searches for libkeyboard.dll file and does not accept the libkeyboard.a file.

  • What do you write on the command line when you compile the Go program? – md2perpe Feb 17 '18 at 23:22
  • 1
    Compilation (linking, specifically) works when the dll is in lib dir because lib dir is specified explicitly as a path to search, in LDFLAGS. At runtime, the os looks for the dll file in conventional locations, one of those happens to be the binary's current dir, so putting the dll in the same dir works. – Mark Feb 18 '18 at 00:46
  • 2
    For static linking, try #cgo LDFLAGS: /path/to/library/file.a – Mark Feb 18 '18 at 00:47
  • @Mark Thanks for the help, is there a way to dynamically route to the link library other than copying the .dll ? – Nikhil Varma Feb 18 '18 at 06:35
  • @md2perpe I simply run **go build hello.go** – Nikhil Varma Feb 18 '18 at 06:38
  • There's a flag `-linkshared` with description "link against shared libraries previously created with -buildmode=shared". Have you tried to add that? – md2perpe Feb 18 '18 at 08:20
  • 2
    @NikhilVarma the various ways to find shared libraries depends on the operating system. [This may help](https://stackoverflow.com/questions/2463243/dll-search-on-windows). – Mark Feb 18 '18 at 10:29

0 Answers0