https://jermine.vdo.pub/go/golang%E4%B8%8Ec%E4%BA%92%E7%9B%B8%E8%B0%83%E7%94%A8%E4%BB%A5%E5%8F%8A%E8%B0%83%E7%94%A8c%E7%9A%84so%E5%8A%A8%E6%80%81%E5%BA%93%E5%92%8Ca%E9%9D%99%E6%80%81%E5%BA%93/
could not determine kind of name for C.foo
tree . ├── sub │ ├── foo.go │ ├── foo.h │ └── hello.c └── test ├── main └── main.go
root@ubuntu:~/go_c# tree . ├── sub │ ├── foo.go │ ├── foo.h │ └── hello.c └── test ├── main └── main.go 2 directories, 5 files root@ubuntu:~/go_c# cat sub/foo.go package sub /* #cgo CFLAGS: -Wall extern void foo(); void __attribute__((constructor)) init(void) { foo(); } */ import "C" // AlwaysFalse is here to stay false // (and be exported so the compiler doesn't optimize out its reference) func init() { C.init() } root@ubuntu:~/go_c# cat sub/hello.c #include <stdio.h> #include "foo.h" int count = 6; void foo(){ printf("I am foo!\n"); }root@ubuntu:~/go_c# cat sub/foo.h int count; void foo();root@ubuntu:~/go_c#
root@ubuntu:~/go_c# cat test/main.go package main import "fmt" import "C" import _ "../sub" func init() { fmt.Println("init in main.go ") } func main(){ fmt.Println("Hello c, welcome to go!") }
root@ubuntu:~/go_c/test# ./main I am foo! I am foo! init in main.go Hello c, welcome to go! root@ubuntu:~/go_c/test#
package main import "fmt" //import "C" //import _ "../sub" func init() { fmt.Println("init in main.go ") } func main(){ fmt.Println("Hello c, welcome to go!") }
root@ubuntu:~/go_c/test# go build main.go root@ubuntu:~/go_c/test# ./main init in main.go Hello c, welcome to go! root@ubuntu:~/go_c/test#
root@ubuntu:~/go_c/test# cat ../sub/foo.go package sub /* #cgo CFLAGS: -Wall extern void foo(); void __attribute__((constructor)) init(void) { foo(); } */ import "C" var AlwaysFalse bool // AlwaysFalse is here to stay false // (and be exported so the compiler doesn't optimize out its reference) func init() { if AlwaysFalse { C.init() } }
root@ubuntu:~/go_c/test# go build main.go # _/root/go_c/sub cgo-gcc-prolog: In function ‘_cgo_b2a0b4a5114f_Cfunc_init’: cgo-gcc-prolog:47:33: warning: unused variable ‘_cgo_a’ [-Wunused-variable] root@ubuntu:~/go_c/test# ./main I am foo! init in main.go Hello c, welcome to go!