golang调用c++文件

简要步骤:

1,将c++ 的方法提取到头文件.h中( )

2,编译cc(c++)文件为动态链接库so文件  gcc -fPIC -shared hello.c -o libhello.so 

3,将头文件放入include目录 .so放入lib目录

4,go程序中指定 CFLAGS 和 LDFLAGS

#cgo  CFLAGS:  -I  ./include 
#cgo  LDFLAGS:  -L .b  -lhello   -Wl,-rpath,/usr/localb  

5,运行(go 程序的时候)发布时候指定 export LD_LIBRARY_PATH="lib文件所在目录" (`pwd`)

export LD_LIBRARY_PATH=./lib

 目录结构: 

|-project
|  |-lib
|  |  |-libhello.so
|  |-include
|  |  |-hello.h
|  |-src
|  |  |-main.go
|  |-pkg
|  |-bin

编译为so文件

g++ -g -Wall -lssl -lcrypto -c decrypter.cc -fPIC -shared -o libdecrypter.so

go文件:

 package main  

/* 
#cgo  CFLAGS:  -I  ./include 
#cgo  LDFLAGS:  -L ./lib  -lhello 
#include "hello.h" 
*/  
import "C"  
func main() {  

        C.hello(C.CString("call C hello func"))  
}  

 hello.c

#include "hello.h"
#include <stdio.h>

void hello(const char *str)
{
        printf("%s(%d): %s
", __FUNCTION__, __LINE__, str);
}

hello.h

#ifndef ___HELLO___
#define __HELLO___
void hello(const char *str);
#endif

编译: go build main.go 

编译如果出错:  

# command-line-arguments
/tmp/go-build471704263/command-line-arguments/_obj/xx.cgo2.o: In function `_cgo_7f644bb4ca7c_Cfunc_xxxx':
请一定检查so文件是否为libxxx.so 
 
编译如果报错 could not determine kind of name for C.xxx
请检查 import "C" 是不是紧挨着 go顶部头文件c++ 部分注释代码
 

运行:  ./main

运行如果出现:     error while loading shared libraries: xxx.so: cannot open shared object file: No such file or directory

 请一定要 export LD_LIBRARY_PATH="动态链接文件所在目录"  

其他说明:golang的注释中直接写函数内容的方式只支持c不支持C++  

package main  
//!!!!以下为c代码不支持c++ 
    /* 
#include <stdio.h> #include <stdlib.h> #include <unistd.h> void hello(const char *str) { printf("===> %s(%d): %s ", __FUNCTION__, __LINE__, str); }
*/ import "C" func main() { C.hello(C.CString("call C hello func")) }

参考文章:golang的cgo支持调用C++的方法

golang之cgo---调用C/C++动态库函数

http://doumadou.github.io/golangdiao-yong-ccfang-fa.html  (需要步骤五才能运行成功) 

附件:下载

 

原文地址:https://www.cnblogs.com/lavin/p/golang-call-cpp-or-cc-file.html