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)

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


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?

2 answers

  • answered 2018-07-11 05:05 caszi

    Could you have:



    And in each file, have the correct #cgoflags (but the same code)?

    Depending on the target OS, go will build only the correct file (see here)

  • answered 2018-07-11 05:14 Anuruddha

    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/darwin -lprocessing_lib

    we can also pass the Architecture if needed like below

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