【发布时间】:2017-10-27 10:57:01
【问题描述】:
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 library)
之后我制作了一个简单的应用程序,它将使用这个库(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 Release 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\\ 文件夹的内容:
我尝试从我的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 提取object files (*.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 的库。
感谢您的帮助。
【问题讨论】:
-
“我还尝试从库 libmath.core.a 中提取目标文件 (*.o),我得到了 ... main.o”
main.o文件是从您的 C++ 源代码生成的。它在图书馆档案中的唯一方法是你自己把它放在那里。 -
另外,我非常怀疑 Go 使用 C++ 兼容的名称修饰。一般来说,它似乎是impossible to directly call Go from C,所以在 C++ 中也不可能。
标签: c++ go static-libraries static-linking