8

I'm trying to compile the following code on a MacOS machine

// #cgo darwin LDFLAGS: -L${SRCDIR}/build/darwin -lprocessing_lib
// #cgo linux LDFLAGS: -L${SRCDIR}/build/linux -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
}

I have the libprocessing_lib.so file in the correct location defined in the LDFLAGS. However the compiler still throws an error saying

dyld: Library not loaded: build/lib_processing_lib.so
  Referenced from: /Users/ag/workspace/src/github.com/apremalal/pq-processor/./pq-processor
  Reason: image not found

Once I copy build/lib_processing_lib.so to the root of the project it works.

It seems that the library directory provided by the LDFLAGS is somehow getting overridden.

I've noticed that setting DYLD_LIBRARY_PATH variable before compilation also override this value.(I ran above scenarios without setting this parameter)

Interestingly though the same code works in Linux environment by picking up the correct path.

Is there anything special that I need to do in MacOS to get the desirable LDFLAGS behavior?

Anuruddha
  • 3,187
  • 5
  • 31
  • 47
  • Try running `go build` with the `-x` flag and see whether the calls to the C compiler indeed use the value you'd expect. – kostix Jul 12 '18 at 07:01
  • Also, you might just have found a bug. [This search](https://github.com/golang/go/issues?utf8=%E2%9C%93&q=is%3Aissue+in%3Atitle+label%3AOS-Darwin+cmd%2Fcgo) does not bring anything matching so you may just try filing an issue. – kostix Jul 12 '18 at 07:07

2 Answers2

2

Set the dynamic library load path.For mac setting DYLD_LIBRARY_PATH for linux LD_LIBRARY_PATH

momo0853
  • 29
  • 3
0

I had the same issue. Fixed by building the lib with gcc from the root folder

Make file:

LIB = lib #source code of the lib
LIB_SO = ...
UNAME := $(shell uname)

ifeq ($(UNAME), Darwin)
BIN_PATH = build/darwin
endif

ifeq ($(UNAME), Linux)
BIN_PATH = build/linux
endif

build:
    gcc -c -O2 -Werror -fpic -o $(BIN_PATH)/ccr.o $(LIB)/ccr.c
    gcc -shared -o $(BIN_PATH)/$(LIB_SO) $(BIN_PATH)/ccr.o

If you build that way no LD_LIBRARY_PATH/DYLD_LIBRARY_PATH needed.

Andrei Schneider
  • 3,618
  • 1
  • 33
  • 41