大家好,今天本人给大家带来文章《在 Golang 中如何使用 cgo 来连接到 math.h 的 C 库?》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!
我目前正在尝试使用 cgo 为 novas c 包(天体测量/天文学包)构建 golang 包装器。 novas 本质上是通过将源文件放置在您正在工作的任何目录中(不存在已编译的库文件)来“安装”的,因此我相信我需要包含我将使用的 .c 文件(位于文件夹一中) .go 文件下的目录。
novas.c 中的函数。然而,该程序无法编译,显然是因为 math.h 中存在多个对函数的未定义引用;这很奇怪,因为 math.h 包含在我的 .go 文件和我打算使用的 c 文件中。
go run novastest.go # command-line-arguments /tmp/go-build681583835/b001/_x002.o: in function `equ2gal': ./cdist/novas.c:1995: undefined reference to `sincos' ./cdist/novas.c:1996: undefined reference to `sincos' ./cdist/novas.c:2033: undefined reference to `atan2' ./cdist/novas.c:2025: undefined reference to `atan2' ./cdist/novas.c:2022: undefined reference to `sqrt' /tmp/go-build681583835/b001/_x002.o: in function `era': ./cdist/novas.c:3242: undefined reference to `fmod' ./cdist/novas.c:3242: undefined reference to `fmod' ...(etcetera)
我在 virtualbox vm 实例中的 ubuntu 18.04 (x64) 上运行。我在这里错过了特定的一行吗?
我的go 程序如下所示:
package main
/*
#include "cdist/novas.h"
#include "cdist/novas.c"
#include "cdist/novascon.c"
#include "cdist/nutation.c"
#include <math.h>
*/
import "c"
import "log"
func main() {
log.println("test of novas function")
var julianhigh c.double
var julianlow c.double
...
var z c.double
// test values
julianhigh = 2458953.5
julianlow = 1.0
...
z = -1.437110810486059e+03
vcel := make([]c.double,0) //create the array to pass to the function.
vcel = append(vcel, x)
...
vterfirst := &(vter[0])
c.cel2ter(julianhigh,julianlow,deltat,method,accuracy,option,polarx,polary,vcelfirst,vterfirst)
log.println("c function completed processing.")
}
c 程序太大,无法包含,因此我将显示 novas.h 文件和 novas.c 文件的相关部分。
c 文件:
/*
...
novas.c: main library
...
*/
#ifndef _novas_
#include "novas.h"
#endif
#include <math.h>
... //(other functions follow until the necessary one)
/********cel2ter */
short int cel2ter (double jd_ut_high, double jd_ut_low, double delta_t,
short int method, short int accuracy, short int option,
double xp, double yp, double *vec1,
double *vec2)
/*
------------------------------------------------------------------------
purpose:
this function...
请注意,该函数本身依赖于从我包含的其他文件进行调用的函数。
.h 文件:
/*
...
novas.h: Header file for novas.c
...
*/
#ifndef _NOVAS_
#define _NOVAS_
#ifndef __STDIO__
#include <stdio.h>
#endif
#ifndef __MATH__
#include <math.h>
#endif
#ifndef __STRING__
#include <string.h>
#endif
...解决方案
您需要一个指令来告诉 go 链接器链接到 c 的数学库。标头 math.h 不包含数学函数的实现:仅包含它们的声明(第一近似值)。
无论如何,您需要在 go 文件的注释中添加此行:
#cgo LDFLAGS: -lm
-l 的意思是“与此库链接”,m 是 c 数学库的名称。
以上就是《在 Golang 中如何使用 cgo 来连接到 math.h 的 C 库?》的详细内容,更多关于的资料请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
