I'm trying to call C++ in Go.
sparkle_windows.h:
#ifndef GO_WINSPARKLE_H
#define GO_WINSPARKLE_H
#ifdef __cplusplus
#include <QResource>
#include "winsparkle.h"
extern "C" {
#endif
void initWinSparkle()
{
win_sparkle_set_dsa_pub_pem(reinterpret_cast<const char *>(QResource(":/WinSparkle/dsa_pub.pem").data()));
win_sparkle_init();
}
#ifdef __cplusplus
}
#endif
#endif
main_windows.go:
package main
/*
#cgo CPPFLAGS: -I ${SRCDIR}/WinSparkle/include
#cgo LDFLAGS: -L${SRCDIR}/WinSparkle/Release -lWinSparkle -lsparkle_windows -lstdc++
#include "sparkle_windows.h"
*/
import "C"
func main() {
C.initWinSparkle()
}
and the error:
In file included from .\main_windows.go:10:0:
./sparkle_windows.h: In function 'initWinSparkle':
./sparkle_windows.h:15:30: error: 'reinterpret_cast' undeclared (first use in this function)
win_sparkle_set_dsa_pub_pem(reinterpret_cast<const char *>(QResource(":/WinSparkle/dsa_pub.pem").data()));
cgo doesn't compile C++, so you need to put your c++ function on a .cpp file and compile it using a c++ compiler. Then you produce a library and only put the function prototype on your .h file.
The .h file should be pure C, e.g. You cannot use a c++ type as your function argument.
Here's a simple example (making a static library, on linux using g++ / ar):
cpplink_test/cpp/cpplink.cpp:
#include <iostream>
#include "cpplink.h"
extern "C" void helloCpp()
{
std::cout << "Hello from Cpp !!!!\n";
}
cpplink_test/cpp/cpplink.h:
#ifdef __cplusplus
extern "C" {
#endif
void helloCpp();
#ifdef __cplusplus
}
#endif
Compile and Produce a static library (from cpp/ dir):
g++ -fPIC -c cpplink.cpp
ar cru libcpplink.a cpplink.o
ranlib libcpplink.a
cpplink_test/main.go:
package main
/*
#cgo CPPFLAGS: -I${SRCDIR}/cpp
#cgo LDFLAGS: -L${SRCDIR}/cpp -lcpplink -lstdc++
#include <cpplink.h>
*/
import "C"
import "fmt"
func main() {
fmt.Println("Hello GO")
C.helloCpp()
}
Build and Run:
go build
./cpplink_test
output:
Hello GO
Hello from Cpp !!!!
If you are on windows, it may differ slightly for the C++ library creation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With