
1)swift,貌似官网的推荐
2)extern "C"
我使用后者,用起来比较爽,上代码
c.h
#pragma once #ifdef __cplusplus
extern "C" {
#endif
void test();
#ifdef __cplusplus
}
#endif
c.c
#include "cplus.hpp"
#include "c.h" void test() {
A *a = new B();
a->test();
}
cplus.hpp
#pragma once class A {
public:
virtual void test();
};
class B: public A {
public:
void test();
};
cplus.cpp
#include <iostream>
#include "cplus.hpp" using namespace std; void A::test() {
cout << "a" << endl;
} void B::test() {
cout << "b" << endl;
}
build.sh
g++ -o cplus.o -c cplus.cpp
g++ -o c.o -c c.c
ar r libc_test.so c.o cplus.o
test.go
package main
// #cgo LDFLAGS: -L . -lc_test -lstdc++
// #cgo CFLAGS: -I ./
// #include "c.h"
import "C" func main(){ C.test() }
执行顺序
./build.sh
go build test.go