英文:
how to compile a Golang project correctly with a package that has C code inside
问题
我开始用Golang写一个项目,但是立刻遇到了一个问题。我需要从我的代码连接到硬件,我有一个供应商提供的Golang驱动程序和包装器。包装器连接的描述说需要将代码放在项目的src目录下(我没有使用这样的目录,但我将文件放在了目录./internal/fptr10下的包名中,并且在我的main.go中成功导入)。我在IDE GoLand中看到了这个包内的方法,但是当我尝试编译项目(我调用应该创建驱动程序实例的第一个函数New())时,我得到了错误:fptr10.New()未定义。包装器目录中有两个用C写的头文件,我知道这是一个问题,但是我不知道如何正确编译它。
整个项目,包括库本身,都可以在https://github.com/Natrix31/KKTWatcher上找到。
附注:我在Windows下工作。
我尝试从IDE和命令行使用go build和go install编译项目,但结果都一样。程序无法编译,并显示错误:New()未定义。
英文:
I started writing a project in Golang, but immediately ran into a problem. I need to connect from my code to the hardware, I have a driver and a vendor-provided wrapper for Golang. The description of the wrapper connection says that you need to put the code in the src directory of the project (I don't use such a directory, but I put the files in the directory./internal/fptr10 by package name and in my main.go it is successfully imported). I see the methods inside this package in the IDE GoLand, but when I try to compile the project (I call the very first function that should create an instance of the driver and is called New()) - I get the error: fptr10.New() undefined. There are two header files written in C in the wrapper directory and I understand that there is a problem with them, but I don't understand how to compile it correctly.
The entire project, together with the library itself, is available on https://github.com/Natrix31/KKTWatcher
P.S.: I work under Windows
I tried to compile the project from the IDE, and from the command line using go build and go install
But the result is the same. The program does not compile and gives the error: New() undefined
答案1
得分: 1
对于这种情况,在Go模块中插入C代码,只需确保在您的平台上安装了C编译器,并使用前导注释进行引用。
main.go
/*
#include <stdio.h>
#include <math.h>
#include "calc.h"
*/
import "C"
func main() {
fmt.Println(C.add(1, 2))
}
calc.c
:
#include "calc.h"
int add(int a, int b) {
return a + b;
}
calc.h
:
int add(int a, int b);
Go默认启用CGO,所以只需构建它:
go build -o main.out .
英文:
For this scenario where you can drop the C code inside the Go module just make sure you have the C compiler installed in your platform and make a reference with preamble comments.
main.go
/*
#include <stdio.h>
#include <math.h>
#include "calc.h"
*/
import "C"
func main() {
fmt.Println(C.add(1, 2))
}
calc.c
:
#include "calc.h"
int add(int a, int b) {
return a + b;
}
calc.h
:
int add(int a, int b);
Go has CGO enabled by default so just build it:
go build -o main.out .
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论