英文:
How to include headers from a third party package in Go?
问题
假设我的包工作区中有一个名为github.com/yada/yada
的第三方包。在这个包中,有一个名为yoda.go.h
的头文件,我想要重用它(不确定这是否是一个好主意,但这是一个全新的问题)。我该如何将依赖包中的头文件导入到我的包中?
package main
// #cgo pkg-config: my-dep other-dep
// #include <someHeader.h>
// #include <otherHeader.h>
// #include github.com/yada/yada/yoda.go.h // 不起作用 :(
import "C"
除了是否是一个好主意,我仍然想知道是否可能实现。
PS:如果你认为这真的是一个坏主意,那我应该做些什么呢?
英文:
Let's supose my package workspace has github.com/yada/yada
third party package. Inside this package there is a yoda.go.h
header I would like to reuse (not sure if it's a good idea, but that's a hole new question). How do I import the header from a dependecy package into my own package?
package main
// #cgo pkg-config: my-dep other-dep
// #include <someHeader.h>
// #include <otherHeader.h>
// #include github.com/yada/yada/yoda.go.h // doesn't work :(
import "C"
Apart from being a good idea or not, I still would like to know if it's possible.
PS: If you think it's really a bad idea, what should I do instead?
答案1
得分: 3
使用CGO CFLAGS指令引用额外的包含路径。
//#cgo CFLAGS: -I $GOPATH/src/github.com/yada/yada/
...
//#include "yoda.go.h"
import "C"
更正:
在构建过程中,go工具不会展开$GOPATH变量。相反,应该在那里使用完整路径。更正后的代码如下:
//#cgo CFLAGS: -I /full/path/to/src/github.com/yada/yada/
//#include "yoda.go.h"
英文:
Use CGO CFLAGS directive to reference additional include path.
//#cgo CFLAGS: -I $GOPATH/src/github.com/yada/yada/
...
//#include "yoda.go.h"
import "C"
CORRECTION:
The go tool does not expand $GOPATH variable during build. Instead, the full path should be used there. Corrected code:
//#cgo CFLAGS: -I /full/path/to/src/github.com/yada/yada/
//#include "yoda.go.h"
答案2
得分: 1
可能不是一个好主意直接引用它,因为它不是一个导出的实体,而且可能会发生变化或被删除。
如果你真的需要那个头文件,你将不得不直接在你的本地文件系统中引用它。(当然,你也可以将其复制到你的项目中)
英文:
Probably not a good idea to try and reference it directly, since it's not an exported entity, and is subject to change or removal.
If you really need that header, you'll have to reference it directly in your local filesystem. (of course you're free to copy into your project too)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论