To write some C code in a comment above import "C"
is straightforward:
// 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())
}
And it works fine:
$ go install
$ foo
forty-two == 42
However, C code in it's own .c file:
// foo.c
int fortythree() {
return 43;
}
...referenced from Go:
// foo.go
func main() {
fmt.Printf("forty-two == %d\n", C.fortytwo())
fmt.Printf("forty-three == %d\n", C.fortythree())
}
...does not work:
$ go install
# foo
could not determine kind of name for C.fortythree
The C header file foo.h is missing:
// foo.h
int fortythree();
Reference the header file from Go like this:
// 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())
}
Behold, the power of foo.h:
$ go install
$ foo
forty-two == 42
forty-three == 43
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.