zoukankan      html  css  js  c++  java
  • go与c++链接示例

    go lang与c/c++的链接示例:

    foo.hpp

    //foo.hpp
    #ifndef _FOO_HPP_
    #define _FOO_HPP_
    
    template<typename T>
    T add(const T& lhs,const T& rhs)
    {
    	return lhs+rhs;
    }
    
    void display();
    
    #endif //_FOO_HPP_
    

    foo.cpp

    //foo.cpp
    #include "foo.hpp"
    #include <iostream>
    
    void display()
    {
    	std::cout<<"this message is from foo.cpp -display"<<std::endl;
    }
    

    foo_wrap.h

    //foo_wrap.h
    #ifndef _FOO_WRAP_H_
    #define _FOO_WRAP_H_
    
    #ifdef __cplusplus
    extern "C" {
    #endif
    
    //add function family
    int add_int_wrap(int lhs,int rhs);
    float add_float_wrap(float lhs,float rhs);
    
    //display some message
    void display_wrap();
    
    #ifdef __cplusplus
    }
    #endif
    #endif //_FOO_WRAP_H_
    

    foo_wrap.cpp

    //foo_wrap.cpp
    #include "foo_wrap.h"
    #include "foo.hpp"
    
    //add function family
    int add_int_wrap(int lhs,int rhs)
    {
    	return add<int>(lhs,rhs);
    }
    float add_float_wrap(float lhs,float rhs)
    {
    	return add<float>(lhs,rhs);
    }
    
    //display
    void display_wrap()
    {
    	return display();
    }
    

    foo.go

    //foo.go
    package main
    
    // #cgo CFLAGS: -I./ 
    // #cgo LDFLAGS: -L./ libfoo.a -lstdc++
    // #include "foo_wrap.h"
    import "C"
    import "fmt"
    
    func main() {
    	//test add family
    	//int
    	var a,b int32 = 1,2
    	rsi := C.add_int_wrap(C.int(a),C.int(b))
    	fmt.Printf("C.add_int_wrap(%d,%d)=%d
    ",a,b,rsi)
    	//float
    	var c,d float32 = 1.3,2.5
    	rsf := C.add_float_wrap(C.float(c),C.float(d))
    	fmt.Printf("C.add_int_wrap(%f,%f)=%f
    ",c,d,rsf)
    	
    	//display
    	fmt.Println("message from C:")
    	C.display_wrap()
    }
    

    编译脚本build.sh:

    #!/bin/sh
    #build c/c++ source code g++ -c foo.cpp g++ -c foo_wrap.cpp ar rcs libfoo.a foo.o foo_wrap.o #build go source code go build foo.go ./foo
  • 相关阅读:
    第一次冲刺个人博客03
    第一次冲刺个人博客02
    《梦断代码》阅读笔记01
    “进度条”博客——第十一周
    “进度条”博客——第十周
    “进度条”博客——第九周
    站立会议个人博客10(2016/4/28)
    站立会议个人博客9(2016/4/27)
    站立会议个人博客8(2016/4/26)
    站立会议个人博客7(2016/4/25)
  • 原文地址:https://www.cnblogs.com/xylc/p/4418037.html
Copyright © 2011-2022 走看看