`undefined reference` error occurred when linking dynamic c++ lib with CGO

Viewed 190

I use dynamic libaray written by c++ in my Go code as following:

/*
#cgo CFLAGS: -I include
#cgo LDFLAGS: -L lib -ldemo
#include "demo.h"
*/
import "C"

func main() {
   C.demo() // demo function in c++ library
}

The libdemo.so library depends on the system dynamic libaray such as fontmanager

There are undefined reference errors occurred when I run the Go code, the errors detail as following:

/usr/bin/ld: ./lib/libdemo.so: undefined reference to `FT_GlyphSlot_Own_Bitmap'
/usr/bin/ld: ./lib/libdemo.so: undefined reference to `FT_Get_Color_Glyph_Layer'
/usr/bin/ld: ./lib/libdemo.so: undefined reference to `FT_Get_Glyph_Name'
/usr/bin/ld: ./lib/libdemo.so: undefined reference to `FcLangSetCreate'
/usr/bin/ld: ./lib/libdemo.so: undefined reference to `FcFontSetMatch'
/usr/bin/ld: ./lib/libdemo.so: undefined reference to `FT_Get_X11_Font_Format'
... more ...

I try to use ld command as following:

ld /mycode/lib/libdemo.so   # Same `undefined reference`

ld /usr/lib/x86_64-linux-gnu/font-manager/libfontmanager.so /mycode/lib/libdemo.so 
# Link successful

I guess I should include all dependencies in Go Code, but I don't know how to include the references of dynamic libraries in Go code,or include multiple dynamic library in Go code.

Scene1:

`GoCode` include `DynamicLibA`
`DynamicLibA` include `DynamicLibB`

Scene2:

`GoCode` include `DynamicLibA`
`GoCode` include `DynamicLibB`

FIRST QUESTION: Is this problem caused by not including all the dependent libraries?

SECOND QUESTION: In above 2 scenes, How to include the libraries in Go code?

Please give some suggestion, THANKS A LOT.

1 Answers

Is this problem caused by not including all the dependent libraries?

Yes. More precisely, the libdemo.so was not linked correctly -- it should be linked with -lfontmanager, and wasn't.

ld /usr/lib/x86_64-linux-gnu/font-manager/libfontmanager.so /mycode/lib/libdemo.so

This command is pure nonsense. It doesn't do anything.

The command you want (you should never use ld on a UNIX system, unless you are linking an operating system, a boot loader, or something similar):

gcc -shared -o libdemo.so demo.o -lfontmanager

Related