现有类定义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 << "\t" << units_sold << "\t" << revenue<<"\t"<<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:
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: