doudou5023 2018-02-27 00:37
浏览 35

在Golang项目中正确包含C库(按源)

Currently, I have the following source tree:

client
|
|--cryptlib
|  |
|  |--cryptlib.so
|  |--cryptlib.a
|  |--<C sources>
|  |--Makefile
|
|--impl1
|  |--<C sources>
|  |--impl1.go
|  |--impl1_test.go
|
|--impl2
|  |--<C sources>
|  |--impl2.go
|  |--impl1_test.go
|
|--client.go
|--client_test.go

The cryptlib library is used by both impl1 and impl2 and thus, both impl1.go and impl2.go start with the following cgo block:

/*
#cgo CFLAGS: -I. -I${SRCDIR}/../cryptlib -L${SRCDIR}/../cryptlib -lcryptlib -Ofast 
#cgo LDFLAGS: -L${SRCDIR}/../cryptlib -lcryptlib
*/
import "C"

And this works while trying to test impl1_test.go and impl2_test.go.

However, when trying to run the tests situated in client_test.go, I keep getting errors claiming that the cryptlib library could not be found. I think this may have to do with the fact that ${SRCDIR} in this case is ./client which makes the rest of the CFLAGS and LDFLAGS paths incorrect (./client/../cryptolib).

Although it leads to repetition, I have also tried including cryptlib into impl1 and impl2. This approach again causes issues when trying to test client_test.go since the combined binary now sees multiple instances of the same functions defined in cryptlib.

How should I properly structure my source tree and cgo flags such that all my .go source files can find my cryptlib library and compile?

  • 写回答

1条回答 默认 最新

  • doutizha7526 2018-03-22 13:09
    关注

    From the cgo Godocs:

    When the cgo directives are parsed, any occurrence of the string ${SRCDIR} will be replaced by the absolute path to the directory containing the source file.

    So for client_test the SRCDIR is a directory level higher and therefor its CGO directives should look like this:

    /*
    #cgo CFLAGS: -I. -I${SRCDIR}/cryptlib -L${SRCDIR}/cryptlib -lcryptlib -Ofast 
    #cgo LDFLAGS: -L${SRCDIR}/cryptlib -lcryptlib
    */
    

    As far as another approach, what I normally do is install the C library in the system library directory /usr/lib/. That way i do not need to worry about relative references and can just use -lcryptlib.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看