zoukankan      html  css  js  c++  java
  • ubuntu 中使用makefile组织c++多文件的简陋方法

    现有类定义Sales_item.hpp Sales_item.cpp

    主函数my7_31.cpp(代码来源于c++primer 习题解答7_31)

    希望使用makefile在Ubuntu中进行编译链接,生成可执行文件edit。

    注:目的是了解makefile如何使用,这个makefile文件并不通用,只能体现makefile的基本功能

    代码如下

    Sales_item.hpp

    #pragma once
    #include <iostream>
    #include <string>
    
    class Sales_item
    {
    public:
    	Sales_item() :units_sold(0), revenue(0.0){}
    private:
    	std::string isbn;
    	unsigned int units_sold;
    	double revenue;
    public:
    	
    	bool same_isbn(const Sales_item & rhs)const;
    
    	std::istream & input(std::istream & in);
    	std::ostream & output(std::ostream & out)const;
    	double avg_price() const;
    };
    

     Sales_item.cpp

    #include "Sales_item.hpp"
    
    
    bool Sales_item::same_isbn(const Sales_item & rhs) const
    {
    	return this->isbn==rhs.isbn;
    }
    
    
    std::istream & Sales_item::input(std::istream & in)
    {
    	double price;
    	in >> isbn >> units_sold >> price;
    	if (in)
    	{
    		revenue = units_sold*price;
    	}
    	else
    	{
    		units_sold = 0; revenue = 0.0;
    	}
    	return in;
    	//TODO: insert return statement here
    }
    
    
    std::ostream & Sales_item::output(std::ostream & out) const
    {
    	out << isbn << "	" << units_sold << "	" << revenue<<"	"<<avg_price();
    	return out;
    	//TODO: insert return statement here
    }
    
    
    double Sales_item::avg_price()const
    {
    	if (units_sold)
    		return revenue / units_sold;
    	else
    	{
    		return 0;
    	}
    	
    }
    

     my7_31.cpp

    //main for read class Sales_item
    #include <iostream>
    #include "Sales_item.hpp"
    
    using namespace std;
    
    int main ()
    {
    	Sales_item item;
    	cout << "enter some trasactions(Ctrl+z to end) :" << endl;
    	while (item.input(cin))
    	{
    		cout << "the trnsaction teade is :" << endl;
    		item.output(cout);
    		cout << endl;
    	}
    	return 0;
    }
    

     makefile

    参考:http://www.chinaunix.net/old_jh/23/408225.html

    edit:my7_31.o Sales_item.o
    	g++ -o edit my7_31.o Sales_item.o
    Sales_item.o:Sales_item.cpp Sales_item.hpp
    	g++ -c Sales_item.cpp
    my7_31.o:my7_31.cpp Sales_item.hpp
    	g++ -c my7_31.cpp 
    clean:
    

     上面是原始版本

    简洁版,依赖于make强大的自动推导功能,只需要给出相应的.h依赖项即可

    edit:my7_31.o Sales_item.o
    	g++ -o edit my7_31.o Sales_item.o
    Sales_item.o: Sales_item.hpp
    
    my7_31.o:Sales_item.hpp
    
    clean:
    
  • 相关阅读:
    文件下载链接
    Python Web服务器
    打印字符串替换
    python 将数据写入excel
    python Telnet通讯
    Python 串口通讯
    monkey 原理,环境搭建、命令详解
    Andriod 四大组件,六大布局
    python练习题100例
    Activity的基本概念与Activity的生命周期
  • 原文地址:https://www.cnblogs.com/simayuhe/p/5842868.html
Copyright © 2011-2022 走看看