How to use relative path for LDFLAGS in golang

I am trying to create a golang program that uses a static library (.a file)

directory structure for my project as below

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

flags for cgo in test.go as below

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

when I use the absolute path for LDFLAGS -L, it works fine, but when I change the path to a relative path, for example

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

and then run the command

 go install testserver 

he returns me an error and says that he "cannot find the -L test"

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

+7
source share
2 answers

You cannot currently. The directory changes between the moment the command was created and the binding. For now, you either need to reference the absolute path, or use the CGO_LDFLAGS environment CGO_LDFLAGS .

It was fixed immediately after go1.4, which added the variable ${SRCDIR} , which is replaced by the absolute path to the directory containing the source file during assembly. https://github.com/golang/go/issues/7891 . It will be in go1.5 and you can easily use it now by building Go from source.

+7
source

It is very useful to use $ {SRCDIR} to solve the relative path problem.

In addition, $ {SRCDIR} indicates the absolute path of the current go file . Use the go build -x . command go build -x . to verify 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 

This is incrrect because lib libaes.a finds the same thing as the go file. Then I changed it and went through.

0
source

Source: https://habr.com/ru/post/1211475/


All Articles