How do you statically link a c library in go using cgo?

前端 未结 4 1643
感情败类
感情败类 2020-11-28 23:22

So there\'s a bunch of stuff on the group that suggests you can do this in go (although not on the cgo documentation):

package bridge

import \"fmt\"

// #cg         


        
相关标签:
4条回答
  • 2020-11-28 23:45

    You just have to link with -Ldirectory -lgb.

    $ cat >toto.c
    int x( int y ) { return y+1; }
    $ cat >toto.h
    int x(int);
    $ gcc -O2 -c toto.c
    $ ar q libgb.a toto.o
    $ cat >test.go
    package main
    
    import "fmt"
    
    // #cgo CFLAGS: -I.
    // #cgo LDFLAGS: -L. -lgb 
    // #include <toto.h>
    import "C"
    
    func main() {
      fmt.Printf("Invoking c library...\n")
      fmt.Println("Done ", C.x(10) )
    }
    $ go build test.go
    $ ./test
    Invoking c library...
    Done  11
    
    0 讨论(0)
  • 2020-11-28 23:56

    A straightforward Makefile to link Go code with a dynamic or static library:

    static:
        gcc -c gb.c
        ar -rcs libgb.a gb.o
        go build -ldflags "-linkmode external -extldflags -static" bridge.go
    
    dynamic:
        gcc -shared -o libgb.so gb.c
        go build bridge.go
    

    Directives in bridge.go:

    /*
    #cgo CFLAGS: -I.
    #cgo LDFLAGS: -L. -lgb
    #include "gb.h"
    */
    import "C"
    ...
    
    0 讨论(0)
  • 2020-11-29 00:05

    Try:

    // #cgo LDFLAGS: -l/Users/doug/projects/c/go-bridge/build/libgb.a
    

    You missed the -l in the LDFLAGS directive.

    0 讨论(0)
  • 2020-11-29 00:08

    Turns out my code is 100% fine; it was a copy of Go 1.0; under go 1.1 this works. Under go 1.0, it doesn't.

    (it's a bit lame answering my own question, I know; but the 'use -L -l answers below aren't right either; it had nothing to do with that).

    A working solution example is up on github here for anyone who find's this question later:

    https://github.com/shadowmint/go-static-linking

    in short that looks like:

    CGO_ENABLED=0 go build -a -installsuffix cgo -ldflags '-s' src/myapp/myapp.go
    

    see also: https://github.com/golang/go/issues/9344

    0 讨论(0)
提交回复
热议问题