0

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.

steve landiss
  • 1,833
  • 3
  • 19
  • 30

1 Answers1

1

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\n", 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
steve landiss
  • 1,833
  • 3
  • 19
  • 30