Home     Interfacing     Software     About     Sitemap   
Quick links

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
1. Anyone can make a decision given enough facts.
2. A good manager can make a decision without enough facts.
3. A perfect manager can operate in perfect ignorance.
  Mar. 2021
   Copyright © 1997-2021 Lammert Bies, All rights reserved