CGO ignores the LDFLAGS -L option on MacOS
Asked Answered
C

2

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?

Copulation answered 11/7, 2018 at 10:25 Comment(2)
Try running go build with the -x flag and see whether the calls to the C compiler indeed use the value you'd expect.Midbrain
Also, you might just have found a bug. This search does not bring anything matching so you may just try filing an issue.Midbrain
H
2

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

Hachman answered 27/12, 2018 at 3:57 Comment(0)
V
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.

Vivien answered 21/3, 2023 at 15:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.