. └── src └── cgotest ├── hello │ ├── cpp │ │ └── hellocpp.cpp │ ├── hello.go │ ├── include │ │ └── hellocpp.h │ └── lib │ └── libhellocpp.so └── main.gohellocpp.h
1 2 3 4 5 6 7 8 9 10 11 12 | #ifndef _HELLOCPP_H_ #define _HELLOCPP_H_ #ifdef __cplusplus extern "C" { #endif void SayHello(); #ifdef __cplusplus } #endif #endif |
1 2 3 4 5 6 7 | #include <iostream> #include "hellocpp.h" using namespace std; void SayHello() { cout << "Hello from C++" << endl; } |
cd $GOPATH/src/cgotest/hello mkdir lib g++ -Wall -shared -fpic cpp/hellocpp.cpp -Iinclude -o lib/hellocpp.sohello.go
1 2 3 4 5 6 7 8 9 10 | package hello // #cgo CFLAGS: -Iinclude // #cgo LDFLAGS: -Llib -lhellocpp // #include "hellocpp.h" import "C" func HelloFromCpp() { C.SayHello() } |
1 2 3 4 5 6 7 | package main import "cgotest/hello" func main() { hello.HelloFromCpp() } |
cd $GOPATH export LIBRARY_PATH=$GOPATH/src/cgotest/hello/lib export LD_LIBRARY_PATH=$LIBRARY_PATH go build cgotest ./cgotestOutput:
Hello from C++
No comments:
Post a Comment