1)swift,貌似官网的推荐

2)extern "C"

我使用后者,用起来比较爽,上代码

c.h

1 #pragma once
2 
3 #ifdef __cplusplus
4 extern "C" {
5 #endif
6 void test();
7 #ifdef __cplusplus    
8 }
9 #endif

 

c.c

1 #include "cplus.hpp"
2 #include "c.h"
3 
4 void test() {
5     A *a = new B();
6     a->test();
7 }

 

cplus.hpp

 1 #pragma once
 2 
 3 class A {
 4     public:
 5         virtual void test();
 6 };
 7 class B: public A {
 8     public:
 9         void test();
10 };

cplus.cpp

#include <iostream>
#include "cplus.hpp"

using namespace std;

void A::test() {
    cout << "a" << endl;
}

void B::test() {
    cout << "b" << endl;
}

build.sh

1 g++ -o cplus.o -c cplus.cpp
2 g++ -o c.o -c c.c
3 ar r libc_test.so c.o cplus.o

test.go

 1 package main
 2 // #cgo LDFLAGS: -L . -lc_test -lstdc++
 3 // #cgo CFLAGS: -I ./
 4 // #include "c.h"
 5 import "C"
 6 
 7 func main(){
 8     
 9     C.test()
10     
11 }

执行顺序

1 ./build.sh
2 go build test.go