C/C++动态链接

 

动态库头文件:sales_item.h

#ifndef SALES_ITEM_H
#define SALES_ITEM_H
#include <iostream>
class Sales_item {
public:
        double avg_price() const;
        void setUnits_sold(int units_sold2);
        void setRevenue(double revenue2);
        bool same_isbn(const Sales_item &rhs) const {
                return isbn == rhs.isbn;
        }
        Sales_item():units_sold(0), revenue(0.0){}

private:
        std::string isbn;
        unsigned units_sold;
        double revenue;
};
#endif 

 

编译动态链接库 sales_item.cpp:

#编译源文件

g++ -c sales_item.cpp -o bin/sales_item.obj

#编译动态链接库

g++ -shared -o bin/sales_item.so bin/sales_item.obj

 

#include "sales_item.h"
double Sales_item::avg_price() const {
        if (units_sold)
                return revenue/units_sold;
        else
                return 0;
}

void Sales_item::setUnits_sold(int units_sold2) {
        units_sold = units_sold2;
}

void Sales_item::setRevenue(double revenue2) {
        revenue = revenue2;
}

 

调用:

g++ test_sales_item.cpp bin/sales_item.so -o bin/test_sales_item.o
./bin/test_sales_item.o

 

#include <iostream>
#include "sales_item.h"
int main(){
        Sales_item item;
        item.setUnits_sold(300);
        item.setRevenue(2393.5);
        double result = item.avg_price();
        std::cout << result << std::endl;
        return 0;
}

 

参考:http://www.cnblogs.com/zhoutian6214/archive/2008/11/11/1331646.html

posted @ 2012-09-04 20:40  haiyupeter  阅读(273)  评论(0编辑  收藏  举报