如何在golang中使用LDFLAGS的相对路径 [英] How to use a relative path for LDFLAGS in golang

查看:2449
本文介绍了如何在golang中使用LDFLAGS的相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是golang的新手,我正尝试构建一个使用静态库(.a文件)的golang程序



我的项目的目录结构为以下

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

test.go中的cgo标志如下

  // #cgo LDFLAGS: -L / home / test / testserver / src / testserver -ltest 
// #includetest.h
importC

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

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

,然后运行命令

  go install testserver 

它向我返回一个错误,并说找不到-lte st



我的问题是如何在LDFLAGS中使用相对路径? ,以便我可以在任何路径上构建项目。谢谢!

解决方案

您目前不能。目录在构建命令和链接之间发生变化。现在,您需要链接到绝对路径,或使用 CGO_LDFLAGS 环境变量。



在go1.4之后提交,其中添加了一个 $ {SRCDIR} 变量,该变量在构建时被绝对路径替换为包含源文件的目录。 https://github.com/golang/go/issues/7891 。这将在go1.5中,现在可以通过构建Go来源来轻松使用它。

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!

解决方案

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.

这篇关于如何在golang中使用LDFLAGS的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆