Go中调用C的动态库与静态库

来源:互联网 发布:淘宝店铺租赁平台 编辑:程序博客网 时间:2024/05/16 01:13
转:http://ybxu-123.blog.163.com/blog/static/594737702014818113159247/
最近在学习GO语言,作为一门基于C语言的语言。对于它的语法很快掌握了,其实本人很早就想写一些关于GO的文章了,今天抽空就写一下,费话不说了,直击主题好了。以下代码是在Linux运行的结果,若用GDB调试,最好安装7.1以上版本

  一、Go调用C的动态库:
   1、创建C的头文件
        //  foo.h
        extern int Num;   // 提供给 go调用
        void foo();

    2、创建C的源文件
        // foo.c
          int Num = 6;
          void foo()
         {
             printf("I'm  Langston!\n");
          }

    3、创建go源文件
        // CgoTest project main.go         
         package main

         // #include "foo.h"
          import "C"
          import "fmt"
         
        func main() {
           fmt.Println(C.Num)
           C.foo()
        }

     4、生成动态库(libfoo.so, 在Linux下叫共享库,我口误Go中调用C的动态库与静态库 - Langston - Langstons世界)
        gcc -c foo.c
        gcc -shared -Wl,-soname,libfoo.so -o libfoo.so  foo.o

     5、使用go工具编译项目
         go build
     6、运行生成的执行档
        ./CgoTest

二、Go调用C的静态库:
  只有第3、第4步不一样,其他都一样的。这里只针对这两步做处理。
  3、创建go源文件
     // CgoTest project main.go
     package main
 
     // #cgo LDFLAGS: -L ./ -lfoo
     // #include "foo.h"
     import "C"
     import "fmt"
 
     func main() {
         fmt.Println(C.Num)
         C.foo()
     }

  4、生成静态库(libfoo.a)
      gcc -c foo.c
      ar -rv libfoo.a foo.o


当然你也可以使用GDB来调试本代码,但必须先进行初始化:
               vi   ~/.gdbinit 添加下面一行:
                add-auto-load-safe-path $GOROOT/src/pkg/runtime/runtime-gdb.py
           把$GOROOT替换为你自己的路径就OK了。

当你用bt(breaktrace)命令时,或许还会遇到glibc之类的错误提示。你可以使用以下方法来进行处理:
使用yum install glibc安装,只会安装一些基本库,不包含 glibc-debuginfo
接着再修改“/etc/yum.repos.d/CentOS-Debuginfo.repo”文件的enable=1文件内容如下:# CentOS-Debug.repo## The mirror system uses the connecting IP address of the client and the# update status of each mirror to pick mirrors that are updated to and# geographically close to the client.  You should use this for CentOS updates# unless you are manually picking other mirrors.## All debug packages from all the various CentOS-5 releases# are merged into a single repo, split by BaseArch## Note: packages in the debuginfo repo are currently not signed#[debug]name=CentOS-6 - Debuginfobaseurl=http://debuginfo.centos.org/6/$basearch/gpgcheck=1gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-Debug-6enabled=1保存之后,使用它之前提示的命令  debuginfo-install glibc-x.x-x.xxx.xxx.xxx 安装即可。好了,本文要讲的知识点,告一段落。期待您的保贵意见。
原创粉丝点击