Problems encountered when the Go language calls the c dynamic library
Background: In today's project, you need to call the c dynamic library in go. First, the Code uses Cgo to implement a c function, c Functions call functions and code in the c dynamic library, and an error occurs during compilation and running.
package mode
/* 4 #include "getfid.h" 5 #include "lib_queue_conf.h" 6 #include
7 #include
8 #include
9 #cgo LDFLAGS: -L ./ -ldl -lgetfid 10 #cgo LDFLAGS: -L ./ -ldl -lqueue 11 int cres = 0; 12 key_list_t * querykey(char * data, int len) { 13 qstr_t oemid; 14 oemid.data = data; 15 oemid.len = len; 16 key_list_t * key; 17 key = query_key(&oemid); 18 return key; 19 } 20 void GetFidFromLua(char * url, char * luapath, char * md5, char * version) 21 { 22 // char * md5; 23 // char * version; 24 // md5 = (char *) malloc(129 * sizeof(char)); 25 // version = (char *) malloc(20 * sizeof(char)); 26 memset(md5, 0, 129); 27 memset(version, 0, 20); 28 getfid(url, luapath, md5, version); 29 } 30 */ 31 import "C"
[1] The system first prompts an error without c function definition during compilation.
If there are no lines 9th or 10th in the compiled code, the c function is incorrectly defined.
Models/prepublish. go: 27: Undefined reference to 'getfid'
The cause of this error is that the c function embedded in go has a call to the function in the dynamic library. before calling the function, the compiler does not know where and who the dynamic library is.
For example, you can add lines 9th and 10 in the above Code to specify the dynamic library.
Cgo LDFLAGS:-L./-ldl-lgetfid //-L specifies the library file location-ldl specifies the library file name
[2] After compilation is complete, there is an error in program execution.
Error message: cannot load dynamic library
The cause of this error is that the dynamic library is dynamically loaded as the name suggests, that is, it is loaded when the program is executed. Therefore, if the Path Program of the dynamic library is not specified in the system, an error is reported.
In Linux, configure export LIBRARY_PATH = $ GOPATH/src/Depend: $ LIBARARY_PATH in the environment variable.
/Depend path with dynamic library.
In addition, the Go language is inherently compatible with c code.
Reference Cgo and pack the C code to be implemented with comments before import "C". C. c_func (), supports data type, function and other c-type calls.