我在macOS上,尝试使用从自制软件安装的mingw-w64交叉编译Windows的golang(CGO 1.10)可执行文件。
我有只带有一个函数(SimpleQRDecode)的golang软件包,该函数从我的c++源代码(FindAndDecodeQR,使用zxing c++端口)调用其他函数。
CGO_ENABLED=1 CXX="x86_64-w64-mingw32-g++" CXX_FOR_TARGET="x86_64-w64-mingw32-g++" CC="x86_64-w64-mingw32-gcc" CC_FOR_TARGET="x86_64-w64-mingw32-gcc" GOOS=windows GOARCH=amd64 go build -x
go build
输出包含大量未解析的符号消息,例如libmyqr.a(qrcode.o):qrcode.cpp:(.text+0x79): undefined reference to `operator new(unsigned long long)'
libmyqr.a(qrcode.o):qrcode.cpp:(.text+0x2cb): undefined reference to `std::string::length() const'
libmyqr.a(qrcode.o):qrcode.cpp:(.text+0x4a7): undefined reference to `__cxa_begin_catch'
libmyqr.a(BinaryBitmap.cpp.obj):BinaryBitmap.cpp:(.text+0x5c2): undefined reference to `std::ios_base::Init::~Init()'
libmyqr.a(BinaryBitmap.cpp.obj):BinaryBitmap.cpp:(.xdata+0xc): undefined reference to `__gxx_personality_seh0'
qrcode.go:
package qrcode
/*
#cgo CFLAGS: -I../../native/prefix/include -I../../libmyqr -fPIC
#cgo CXXFLAGS: -I../../native/prefix/include -I../../libmyqr -fPIC
#cgo LDFLAGS: -L../../libmyqr -lmyqr -lstdc++
#include <stdlib.h>
#include <qrcode.h>
*/
import "C"
import (
"errors"
"fmt"
"unsafe"
)
func SimpleQRDecode(rasterData []byte, width, height int) (string, bool, error) {
res := C.FindAndDecodeQR((*C.char)(unsafe.Pointer(&data[0])), C.int(len(data)), C.int(width), C.int(height))
qrcode.h:
#ifdef __cplusplus
extern "C" {
#endif
const char* FindAndDecodeQR(char *raster, int size, int width, int height);
#ifdef __cplusplus
}
#endif
qrcode.cpp:
#include "qrcode.h"
#include <sstream>
#include <zxing/ZXing.h>
#include <zxing/Binarizer.h>
#include <zxing/BinaryBitmap.h>
#include <zxing/Result.h>
#include <zxing/qrcode/QRCodeReader.h>
#include <zxing/common/GreyscaleRotatedLuminanceSource.h>
#include <zxing/common/GlobalHistogramBinarizer.h>
const char* FindAndDecodeQR(char *raster, int size, int width, int height) {
// GreyscaleLuminanceSource
std::ostringstream resStream;
try {
zxing::ArrayRef<char> image(raster, size);
zxing::Ref<zxing::GreyscaleRotatedLuminanceSource> source(new zxing::GreyscaleRotatedLuminanceSource(image, width, height, 0, 0, width, height));
libmyqr.a-由所有zxing编译对象+ qrcode.cpp.o组成的静态库
最佳答案
可能不是您想听到的,但在Mac上交叉编译到Windows的最简单方法是从c/c++
代码构建DLL库,并从go
代码处理此DLL库。在这种情况下,您甚至不需要CGO_ENABLED=1
。go
代码如下所示(未经测试):
// +build windows
package qrcode
import (
"errors"
"fmt"
"syscalls"
"unsafe"
)
var modYourPkg = syscall.NewLazyDLL("yourpkg.dll")
var procFindAndDecodeQR = modYourPkg.NewProc("FindAndDecodeQR")
func SimpleQRDecode(rasterData []byte, width, height int) (string, bool, error) {
res, _, _ := procFindAndDecodeQR.Call(
uintptr(unsafe.Pointer(&rasterData[0])),
uintptr(len(data)),
uintptr(width),
uintptr(height),
)
...
}
有关syscall软件包的更多信息,请参见。
关于c++ - 在macOS主机上与Windows目标的cgo交叉编译golang,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49492589/