Go using the Dynamic library

Source: Internet
Author: User

Transferred from: http://studygolang.com/articles/1441

Recently, we need to do some work on go using the dynamic C + + library, and often encounter the situation where the dynamic library path cannot be found , so take the time to do some experiments to understand go.

One, the sample code directory structure (assuming the code root directory is/home/gdc/cgotest):

----|bin:
----|PKG
----|SRC
--------|main
------------|main.go
--------|oidb
------------|hello
----------------|hello.go:
----------------|api.h
------------|lib
----------------|libapi.so

Second, the Code
Api.h File Contents:

#ifndef __api_h__ #define __api_h__void  hello (); #endif

Hello.go File Contents:

Package Hello /* #cgo CFLAGS:-i./include#cgo ldflags:-L. /lib-lapi#include "api.h"*/"C"func Hello () {C.hello ();}

Main.go File Contents:

" Oidb/hello " Func main () {hello. Hello ();}


Third, the premise

A. Add the code directory to the GOPATH environment variable. --export gopath= $GOPATH:/home/gdc/cgotest

B. environment variable Ld_library_path value is empty



Iv. Some small experiments on the use of the dynamic C/d library in CGO:

A. Depending on the directory organization and file contents above, you can execute go build oidb/hello or go build Oidb/hello anywhere.

Executing go build oidb/hello This command may not be a reaction, but can tell you that the compilation passed.

Executing go build oidb/hello This command creates oidb/hello.a in the Pkg/linux_amd64 directory under the root of the code (created automatically if it does not exist).

OK, it means that the package is ready for others to use. But can others use it normally? Next, do some main.go related experiments.

B. Unfortunately, at this point I am trying to execute go build main or go install main in many places, I will be prompted that I cannot find the libapi.so dynamic library.

But interestingly, when I execute go build main or go install main in lib or Hello directory, it will be successful. Where execute go install main will be generated in the bin subdirectory of the code root directory

A main executable file, go build main generates a main executable program in the current directory. Then when I try to execute the main executable file located in the bin directory, I will prompt for

Not to libapi.so this dynamic library.

Then I try to copy the Lib directory to the bin directory and the code root, and then execute the main executable file under the bin subdirectory, or the libapi.so dynamic library is not found.

Finally, I took the ultimate trick to execute "Export ld_library_path=/home/gdc/cgotest/lib" (I moved the Lib directory to the root of the code), and then it was OK

Run the main executable program.

Then I move the Lib directory to the bin directory and the SRC directory, and then use the Export command to add the new location of the Lib directory to the Ld_library_path environment variable, and then execute main, all can execute normally.

Summary:

The compilation of the main package is understood:

When the main package is compiled or installed, go will be in the current directory at the location where it is located. Then, if it refers to a package that uses a relative directory, it relies on a dynamic library for a C + + library. Then from the current directory, according to the relative location to find the dynamic library. Therefore, the above in the compilation or installation of the main package, except in the Lib or Hello directory successfully compiled, this is because go from the current directory, to its parent directory of the Lib subdirectory to find libapi.so dynamic Library, and then successfully found, thereby by compiling. In fact, not necessarily in the Lib or the Hello directory to compile the main package. Just make sure that there is a subdirectory lib under the parent directory where the main package is compiled, and that the Lib directory has a libapi.so file that can be compiled. For example, I put the Lib directory under the code root, and then I go to the bin directory, and then I can successfully compile or install the main package.

Of course, if you use the "-l" option to set an absolute directory instead of a relative directory when using a dynamic library, then there are not so many restrictions on compiling or installing the main package. You can compile or install in any location.


The main executable executes the understanding:
Regardless of the dynamic library location that you specify in your code with the "-l" option as a relative or absolute directory, to execute this main executable, you add the directory where the dynamic library you are dependent to is in the environment variable Ld_library_path (or the dynamic library Copy to the system default library search path, but the boss does not allow Ah, depressed).

C. Next, do some experiments on directly compiling the Main.go file.
This compilation is the same as compiling the main package-"-l" using relative paths, then you must ensure that the location of the compilation with a relative path can eventually find the dynamic library; "-L" uses an absolute path and can be compiled anywhere.


D. Finally, do some experiments about setting environment variables in go. Because the execution of the main program requires a dependency on the value of the LD_LIBRARY_PATH environment variable.
D1. The first method: Wei Lao, is to write a shell script, in this script first execute the EXPORT statement, the path of the dynamic library into the Ld_library_path. Then run the program again.
Ok. This method passes.

D2. The second method: Set the value of the environment variable in go.

After his own experiment, and then asked Wei Lao, feel that it is impossible. Because when the program starts, the system automatically loads the libraries that the program depends on, and you set the environment variables in the program

The code is not running yet. Of course, you can't find a dynamic library.

A workaround: Manually load the dynamic library yourself.

Refer to the manual loading library for this article http://blog.csdn.net/joker0910/article/details/6103793, which can be used normally.

F. Supplement (2014.07.21).
Forget to do the go test hello this experiment. After experiments, it is found that if the-l in the package uses relative directories to locate the dynamic library, the following two points are required to successfully execute this command:
First, make sure that the location where the command is executed plus the directories that are obtained by the relative directory need to contain the dynamic libraries that depend on them. This is similar to compiling or installing the main package.
Second, you need to add the directory where you depend on the dynamic library to the environment variable Ld_library_path. This is much like executing main.


The contents of the modified Hello.go file are as follows:

Package Hello/*#cgo ldflags:-ldl#include #include #include "api.h" void Hello_c (char* lib_path) {char* func_name= "Hello";        void* libc;        void (*hello_call) ();                if (libc = Dlopen (Lib_path,rtld_lazy)) {Hello_call = Dlsym (libc, func_name); (*hello_call)                ();        Dlclose (LIBC); }}*/Import"C"Import"unsafe"varExtension_dirstring="/home/guess/.davengu_workdir/go_learning/cgo/use_shared_library/src/oidb/lib/"varOidb_apistring="libapi.so"//#cgo ldflags:-l/home/guess/.davengu_workdir/go_learning/cgo/use_shared_library/src/oidb/lib-lapi//#cgo ldflags:-L. /lib-lapifunc Hello () {libpathc:= C.cstring (extension_dir+Oidb_api); Defer C. Free(unsafe.        Pointer (LIBPATHC)); C.hello_c (LIBPATHC);} 

Using the dynamic library in the Go Libraries

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.