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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With