C references to Go functions

120 views
Skip to first unread message

gocss

unread,
Dec 3, 2016, 8:05:18 PM12/3/16
to golang-nuts
I want to call a go function from c.

I have  file main.go:
package  main

import "fmt"
import "C"
//export MyFunction
func MyFunction(arg1 int) int64 {
 fmt.Println("GO:MyFunction", "arg1=", arg1)
 return 1
}

func main() {
 fmt.Println("GO:main")
}

I build this with:
go build  -buildmode=c-archive main.go

c file call.c:
#include <stdio.h>
#include "main.h"

void main() {
  printf("C:main %s\n", "pc");
  MyFunction(1);
}


gcc call.c -L./main.a
/tmp/ccNCGKAS.o: In function `main':
call.c:(.text+0x1e): undefined reference to `MyFunction'
collect2: error: ld returned 1 exit status

MyFunction is found in main.a archive
 nm main.a | grep MyFunction
0000000000000000 T _cgoexp_ca787091a83e_MyFunction
0000000000000060 t main._cgoexpwrap_ca787091a83e_MyFunction
0000000000032660 r main._cgoexpwrap_ca787091a83e_MyFunction.f
00000000000000b0 t main.MyFunction
                 U _cgoexp_ca787091a83e_MyFunction
0000000000000000 T MyFunction

How do I resolve this ?

Ian Lance Taylor

unread,
Dec 5, 2016, 1:37:30 PM12/5/16
to gocss, golang-nuts
On Sat, Dec 3, 2016 at 5:05 PM, gocss <g...@curtissystemssoftware.com> wrote:
>
> gcc call.c -L./main.a

-L./main.a tells the linker to add the directory "./main.a" to the
search path used to resolve -l options. Since there is no such
directory, the option is effectively meaningless.

Just write `gcc call.c main.a`.

Ian
Reply all
Reply to author
Forward
0 new messages