将Go文件集成到现有的C项目中

I have a large project written in C and I wrote a Go script with a function that I would like to call from the C code (C->Go). This same Go function also needs to call some C functions (Go->C).

Here is a simplified look at the project structure:

- src/...
- src/file_c.h
- src/file_c.c
- src/gocode/file_go.go
- src/Makefile

Here is what I would like to do:

  • file_c.c needs to include file_go.h (C->Go).
  • file_go.go needs to include file_c.h (Go->C).
  • The C software has its own large Makefile and I would like to keep using that one to compile it. The final binary to run will also be from the existing C code (and will call a Go function during its execution).

What I tried so far:

In file file_go.go, prior to the import "C" statement, I added these lines:

// #cgo CFLAGS: -I..
// #include "file_c.h"

Then I tried to compile the file_go.go with both commands:

go build -buildmode=c-shared file_go.go
go build -buildmode=c-archive file_go.go

However, in both cases I get error messages of the sort undefined reference to func, where func is the C function (declared in file_c.h and defined in file_c.c) called from the Go code.

If I remove the calls from Go->C in file_go.go, then it compiles correctly and I can include file_go.h in the C Makefile properly. However, I need the Go file to call that C function too.

How can I build the Go file in such a way that the C function is correctly linked?