如何在go包之间共享C代码?

时间:2019-06-28 18:56:25

标签: go cgo

如何在软件包之间共享C代码?当我尝试从另一个包中包含头文件时,我得到:

Undefined symbols for architecture x86_64:
  "_module2_c_func", referenced from:
      __cgo_b9b83c92221d_Cfunc_module2_c_func in _x002.o
     (maybe you meant: __cgo_b9b83c92221d_Cfunc_module2_c_func)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

我的代码:

main.go:

package main
import (
    "cgo_sample/module1"
    "cgo_sample/module2"
)
func main() {
    module1.Module1_invoke_c_func()
    module2.Module2_invoke_c_func()
}

module1 / module1.go:

package module1
/*
    #include "../module2/module2.h"
 */
import "C"
func Module1_invoke_c_func() int {
    return int(C.module2_c_func())
}

module2 / module2.go:

package module2
/*
  #cgo CFLAGS: -g -Wall
  #include "module2.h"
*/
import "C"
func Module2_invoke_c_func() int {
    return int(C.module2_c_func())
}

module2 / module2.h:

 #ifndef _MODULE1_H_
 #define _MODULE1_H_
   int module2_c_func();
 #endif

module2 / module2.c:

 #include "module2.h"
int module2_c_func() {
    return 12;
}

0 个答案:

没有答案