Use Go code in c/c++ applications

April 27, 2019 — 2 Min Read



This simple tutorial will show how is possible to call GoLang functions from a c/c++ code.

The code written for this example is in a Github repo.

Go library

First thing to do is to write the code for our Go library, in this example it will just contain a simple method that will print a custom hello message based on the input.

So create a main.go file in your project root:

package main

import (
  "C"
  "fmt"
)

//export HelloWorld
func HelloWorld(name string) {
  fmt.Printf("Hello %s\n", name)
}

func main() {}

Note the //export HelloWorld comment, it is used to tell the go compiler to export the specified function, so that it will be available externally.

The library must use the package main and have an empty main function, otherwise it will fail to compile.

To generate the library to use in your c/c++ code use:

go build -buildmode=c-archive -o build/golib.a main.go

The output library will be in build/golib.a, the compiler will also generate an header file (golib.h) to include in the C++ code.

C++ application

#include "golib.h"

int main(int argc, char **argv) {
  char message[] = "World!!!";
  GoString goMessage = {message, sizeof(message)};
  HelloWorld(goMessage);
  return 0;
}

This is a simple c++ main that includes the library and only creates a string to pass to the library method.

To build and link it against the Go library just run:

gcc -I build -pthread main.c build/golib.a -o build/test

The output will be the application executable build/test, that can be easily run:

build/test

Source: https://stackoverflow.com/questions/32215509/using-go-code-in-an-existing-c-project



Share this


comments powered by Disqus