Calling C from Go
After having been a C programmer for thirty+ years, I have created a lot of tested and reusable routines in that programming language. It would be nice if this code could be reused in Go programs. This is relatively easy possible by importing the code in a Go program and executing it.
Let’s assume we have a C function supermath() which accepts two values, prints the sum of the values to stdout and returns the product of the two values.
#include <stdio.h>
#include "supermath.h"
// Copyright (C) 2021 - Lammert Bies
// Distributed under terms of the MIT license.
int supermath( int val1, int val2 ) {
printf( "The sum of %d and %d is %d\n", val1, val2, val1+val2 );
return val1 * val2;
} /* supermath */
To use the function, in the Go program, we have to do two things. First of all, we have to import the C source. This is possible by adding a comment line with a C #include statement and the name of the source file. Then we need to tell the compiler to import this as C code. the import “C” statement will do that for us.
This is a tricky situation though. If you are used to add empty lines in a source file to enhance readability, the compiler may throw unexpected errors. An empty line between the include of the C source and the import “C” statement will produce the error “could not determine kind of name for C.supermath”. This shows that importing C code is a kind of afterthought in the Go language. It works, but it is quirky and you need to know what you are doing. The good thing of being a C programmer is that you probably already know what you are doing because the language doesn’t have much protections in place to prevent bad programming.
package main
// Copyright (C) 2021 - Lammert Bies
// Distributed under terms of the MIT license.
// #include "supermath.c"
import "C"
import "fmt"
func main() {
fmt.Printf( "Let's do some supermath!\n\n" )
result := C.supermath( 3, 4 )
fmt.Printf( "The result of the C function is %d\n", result )
} /* main */
This code can either be built as a standalone executable, or directly run as script from the commandline. In both cases, the program produces the following output:
$ go run cingo.go
Let's do some supermath!
The sum of 3 and 4 is 7
The result of the C function is 12
If you change lines, the one you just left will start to move faster than the one you are now in.
O'BRIEN'S VARIATION ON ETORRE'S OBSERVATION
|