Search code examples
gocgo

Dynamically pickup the correct OS and processor architecture using CGO


I have access only to a linux and darwin distributions of dynamically linked shared libraries.

Following is how I've integrated the library with Golang

// #cgo LDFLAGS: -L${SRCDIR}/build -lprocessing_lib
// #include "Processing-bridge.h"
// #include <stdlib.h>
import "C"
import "unsafe"

type ProcessorWrapper struct {
    ptr unsafe.Pointer
}

func init() {
    pr.ptr = C.NewProcessor()
}

func GetDefault() (id int, name string) {
    var default = C.GetDefault(pr.ptr)
    id = int(default.materialId)
    name = C.GoString(default.name)
    return
}

This works perfectly fine when I copy the matching library under the build/ folder.

I'm trying to make this as a go gettable library , where it could work on both linux and darwing architectures.

Problem I'm having is to tell go compiler to pick the right library for the matching GOOS and GOARCH.

I tried having a folder structure like below

build/darwing/libprocessing_lib.so
build/linux/libprocessing_lib.so

And modified the LDFLAGS as below

// #cgo LDFLAGS: -L${SRCDIR}/build/${GOOS} -lprocessing_lib

However it doesn't recognise ${GOOS} and replace it with the correct value.

Is there a way to achieve this dynamic library pickup feature?


Solution

  • Found an easy way to achive this without creating multiple files by looking at the go source code it self cgo

    // #cgo darwin LDFLAGS: -L${SRCDIR}/build/darwin -lprocessing_lib
    // #cgo linux LDFLAGS: -L${SRCDIR}/build/linux -lprocessing_lib
    

    we can also pass the Architecture if needed like below

    // #cgo darwin,arm64 LDFLAGS: -L${SRCDIR}/build/darwin -lprocessing_lib