How to use a relative path for LDFLAGS in golang

2019-03-28 02:41发布

问题:

I am new to golang , and I am trying to build a golang program which uses a static lib (.a file)

the directory struct for my project as below

└─testserver
    ├─bin
    ├─pkg
    └─src
        ├─logging
        └─testserver
            ├─libtest.a
            └─test.go

the flags for cgo in test.go as below

// #cgo LDFLAGS: -L /home/test/testserver/src/testserver -ltest
// #include "test.h"
import "C"

when I am using absolute path for LDFLAGS -L, it works fines, but when I change the path to a relative path, eg

// #cgo LDFLAGS: -L ./testserver -ltest

and then run the command

go install testserver

it returns an error to me, and says "cannot find -ltest"

my question is how can I use a relative path in LDFLAGS ? , so that I can build the project in any path. Thanks!

回答1:

You currently can't. The directory changes between the time the command is built, and linking. For now you either need to link to an absolute path, or use the CGO_LDFLAGS environment variable.

There was a commit just after go1.4 which added a ${SRCDIR} variable which is replaced by the absolute path to the directory containing the source file at build time. https://github.com/golang/go/issues/7891. This will be in go1.5, and you can easily use it now by building Go from source.



回答2:

It's really very great to use ${SRCDIR} to solve the problem of relative path.

In addition, the ${SRCDIR} indicates the absolute path of current go file. Use command go build -x . to check the output.

$ go build -x .
...
cd /root/sourcecode/src/tcp/aes
CGO_LDFLAGS="-g" "-O2" "-L/root/sourcecode/src/tcp/aes/aes" "-laes" /usr/local/go/pkg/tool/linux_amd64/cgo -objdir $WORK/tcp/aes/_obj/ -importpath tcp/aes -- -I $WORK/tcp/aes/_obj/ aes.go
cd $WORK
...
$ tcp/aes
/usr/bin/ld: cannot find -laes
collect2: error: ld returned 1 exit status

It's incrrect, because the lib libaes.a locates the same as the go file. Then I changed it, and passed.