dongtanjian9310 2018-01-05 00:55
浏览 24
已采纳

如何在未定义main()的情况下让cgo生成目标文件?

I have a project written entirely in C. I just need to call one function which will have to be coded in GO. Therefore I am using cgo to build C files and then I would like to use the resulting object files to link with my main C project.

Assume I have a single file foo.go with a single function func HelloWorld(). I wish to execute this function from my C code.

So I do the following steps

# go tool cgo foo.go
# cd _obj && gcc -c *.o

Now I have two files:

# _cgo_export.o  _cgo_main.o

However, main() is getting somehow defined in there and I cannot link these object files with my main project (multiple mains).

How do I get cgo to not put in a dummy main? Or am I doing this entirely wrong?

EDIT I need the entry point to be in C. The suggestions others have posted require the entry point to be in GO. I have posted the correct solution below, thanks to another user whom I have credited.

  • 写回答

1条回答 默认 最新

  • drby30217 2018-01-05 03:35
    关注

    This answer from @alexander (https://stackoverflow.com/users/131264/alexander) is what solved the problem.

    It is not a confusing proposition if you use gccgo. This works here:

    foo.go

    package main
    
    func Add(a, b int) int {
        return a + b
    }
    

    bar.c

    #include <stdio.h>
    
    extern int go_add(int, int) __asm__ ("example.main.Add");
    
    int main() {
      int x = go_add(2, 3);
      printf("Result: %d
    ", x);
    }
    

    Makefile

    all: main
    
    main: foo.o bar.c
        gcc foo.o bar.c -o main
    
    foo.o: foo.go
        gccgo -c foo.go -o foo.o -fgo-prefix=example
    
    clean:
        rm -f main *.o
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效