如何在CGO中使用外部.c文件?

Jac*_*ble 2 c import go cgo

在上面的注释中编写一些C代码import "C"很简单:

// foo.go
package main

/*
int fortytwo() {
    return 42;
}
*/
import "C"
import "fmt"

func main() {
    fmt.Printf("forty-two == %d\n", C.fortytwo())
    fmt.Printf("forty-three == %d\n", C.fortythree())
}
Run Code Online (Sandbox Code Playgroud)

它工作正常:

$ go install
$ foo
forty-two == 42
Run Code Online (Sandbox Code Playgroud)

但是,C代码在它自己的.c文件中:

// foo.c
int fortythree() {
  return 43;
}
Run Code Online (Sandbox Code Playgroud)

...从Go引用:

// foo.go
func main() {
    fmt.Printf("forty-two == %d\n", C.fortytwo())
    fmt.Printf("forty-three == %d\n", C.fortythree())
}
Run Code Online (Sandbox Code Playgroud)

......不起作用:

$ go install
# foo
could not determine kind of name for C.fortythree
Run Code Online (Sandbox Code Playgroud)

Jac*_*ble 6

缺少C头文件foo.h:

// foo.h
int fortythree();
Run Code Online (Sandbox Code Playgroud)

从Go引用头文件,如下所示:

// foo.go
package main

/*
#include "foo.h"

int fortytwo() {
    return 42;
}
*/
import "C"
import "fmt"

func main() {
    fmt.Printf("forty-two == %d\n", C.fortytwo())
    fmt.Printf("forty-three == %d\n", C.fortythree())
}
Run Code Online (Sandbox Code Playgroud)

看哪,foo.h的力量:

$ go install
$ foo
forty-two == 42
forty-three == 43
Run Code Online (Sandbox Code Playgroud)