Tuesday, March 13, 2018

Calling C functions from Go

Sometimes we need to call C function from Go to get more performance and to reuse existing C/C++ libraries in Go application by automatically generating c-go bindings for a given set of C headers and the manifest file.

Let's try to create an example on how to call C function from Go by using static go libraries.

This sample has been tested on Ubuntu 16.04 LTS.

create folder call_c_doubler and create file as below

filename:Makefile
.PHONY: clean all

all:c_static_lib go_executable

c_static_lib:
    gcc -c doubler/*.c
    ar rs doubler.a *.o
    rm -rf *.o

go_executable:
    go build -o call_c_doubler
   
clean:
    rm -rf *.o *.a call_c_doubler

   
   
filename: main.go
package main

import "fmt"

// #cgo CFLAGS: -I${SRCDIR}/doubler
// #cgo LDFLAGS: ${SRCDIR}/doubler.an
// #include <stdlib.h>
// #inclue <libdoubler.h>
import "C"

func main() {
    fmt.Printf("Enter Go...\n")
    fmt.Printf("Double : %d\n", C.double_it(2))
    fmt.Printf("Exit Go...\n")
}



In folder call_c_doubler/doubler and create file as below
filename:libdoubler.c
#include "libdoubler.h"
#include <stdio.h>

int double_it(int x) {
    printf("Calling C function");
    return 2 * x;
}




filename:libdoubler.h
#ifndef DOUBLER_H
#define DOUBLER_H

int double_it(int x);

#endif



Then just run command make in your terminal to compile the program




Other topics: