c++ - 如何从 C++ 项目静态链接 golang 的 .a 库?

标签 c++ go static-libraries static-linking

Golang 有很多有用的库,但我需要支持我的 C++ 应用程序并且不能用 Golang 重写它(它太大了)。

所以我尝试通过静态链接从我的 C++ 应用程序中使用 Go 的库($GOPATH\pkg\path\to\package\*.a 文件)。

首先我制作了一个简单的库(Golang):

    package math_core
    func Sum(a, b int) int {
        return a + b
    }

并通过以下命令构建此代码(在该项目的根文件夹中):

    SET GOOS=windows
    SET GOARCH=386
    go build
    go install

(结果我得到了 libmath.core.a 库)

之后我制作了将使用该库的简单应用程序 (C++):

    #include <iostream>
    extern int Sum(int a, int b);
    int main() {
        std::cout << Sum(5, 7) << std::endl;
        return 0;
    }

我在网上找到这篇文章:

但这对我没有帮助。

我使用以下软件:

  • Windows 10 x64
  • 面向 C/C++ 开发人员的 Eclipse IDE(Neon.3 4.6.3 版)
  • GCC 版本 4.8.1 20130324(预发布)(rubenvb-4.8-stdthread)
  • Gogland 1.0 EAP(构建号#GO-173.3415.23)
  • JRE 1.8.0_152-release-1024-b6 amd64
  • 转到 1.9.2 windows/amd64

Z:\\MyProjects\\Math.Console\\ 文件夹的内容:

Files structure

我试图从我的 math.console 应用程序使用以下命令静态链接 libmath.core.a 库:

    g++ -O0 -g3 -Wall -c -fmessage-length=0 -o main.o "..\\main.cpp" 
    g++ "-LZ:\\MyProjects\\Math.Console" -o Math.Console.exe main.o -lmath.core

但我得到了这个输出:

`Z:\MyProjects\Math.Console/libmath.core.a: could not read symbols: Archive has no index; run ranlib to add one

我还尝试通过

从库libmath.core.a中提取目标文件(*.o)
    ar -xo libmath.core.a

我得到了以下文件:

    __.PKGDEF
    _go_.o
    main.o

当我试图通过 nm 查看它的内容时,我得到了这个:

    nm: __.PKGDEF: File format not recognized
    nm: _go_.o: File format not recognized

对于 libmath.core.a 库中的 main.o 文件,我得到了这个:

00000000 b .bss
00000000 d .ctors
00000000 d .data
00000000 N .debug_abbrev
00000000 N .debug_aranges
00000000 N .debug_info
00000000 N .debug_line
00000000 N .debug_macro
00000000 N .debug_str
00000000 r .eh_frame
00000000 r .rdata$zzz
00000000 t .text
         U ___main
00000058 t ___tcf_0
00000097 t __GLOBAL__sub_I_main
         U __Z3Sumii
0000006a t __Z41__static_initialization_and_destruction_0ii
         U __ZNSolsEi
         U __ZNSolsEPFRSoS_E
         U __ZNSt8ios_base4InitC1Ev
         U __ZNSt8ios_base4InitD1Ev
         U __ZSt4cout
         U __ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
00000000 b __ZStL8__ioinit
         U _atexit
00000000 T _main

但我不明白如何在 C++ 项目中使用 Golang 的库。

感谢您的帮助。

最佳答案

我相信您需要将导出的函数放在 main 包中。

此外,我认为您需要在该文件中有一个空的 main 函数。

func main() {}

关于c++ - 如何从 C++ 项目静态链接 golang 的 .a 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46973463/

相关文章:

c++ - 强制非限定名称成为依赖值

c++ - QT ofstream 使用变量作为路径名

xcode - 是否可以在没有链接到的静态库的符号的情况下构建动态框架?

c++ - 没有名为 'argument_type' 的类型

c++ - 随机洗牌和函数指针

google-app-engine - "goapp build"工作,但 "appcfg.py update"只是 "can' t 找到导入“......?

c - 在 Code::Blocks 中链接静态系统库 libm.a

c++ - QT静态库未定义对静态变量的引用

go - nsqjs 客户端,不立即从 go-nsq 服务器端接收消息

jquery - JSON 中的意外标记 {