登录
首页 >  Golang >  Go问答

在 Golang 中如何使用 cgo 来连接到 math.h 的 C 库?

来源:stackoverflow

时间:2024-02-26 22:33:25 287浏览 收藏

大家好,今天本人给大家带来文章《在 Golang 中如何使用 cgo 来连接到 math.h 的 C 库?》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我目前正在尝试使用 cgo 为 novas c 包(天体测量/天文学包)构建 golang 包装器。 novas 本质上是通过将源文件放置在您正在工作的任何目录中(不存在已编译的库文件)来“安装”的,因此我相信我需要包含我将使用的 .c 文件(位于文件夹一中) .go 文件下的目录。

因此,我尝试通过创建一个测试 .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 
*/
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 
... //(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 
   #endif

   #ifndef __MATH__
      #include 
   #endif

   #ifndef __STRING__
      #include 
   #endif
   ...

解决方案


您需要一个指令来告诉 go 链接器链接到 c 的数学库。标头 math.h 不包含数学函数的实现:仅包含它们的声明(第一近似值)。

无论如何,您需要在 go 文件的注释中添加此行:

#cgo LDFLAGS: -lm

-l 的意思是“与此库链接”,m 是 c 数学库的名称。

以上就是《在 Golang 中如何使用 cgo 来连接到 math.h 的 C 库?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>