如何在Golang中为LDFLAGS使用相对路径

我试图建立一个golang程序使用静态库(。一个文件) 项目的目录结构如下:
└─testserver
    ├─bin
    ├─pkg
    └─src
        ├─logging
        └─testserver
            ├─libtest.a
            └─test.go

test.go中cgo的标志如下:

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

当我为LDFLAGS -L使用绝对路径时,它可以正常工作,但是当我将路径更改为相对路径时,例如

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

然后运行命令

go install testserver

它返回一个错误给我,并说“找不到-ltest” 我的问题是如何在LDFLAGS中使用相对路径?,这样我就可以在任何路径上构建项目。

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.

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.