打开VS2010,建立一个win32控制台程序,然后打开项目--Tv属性(如图1),打开Tv属性页(如图2),在右边配置类型处选择静态库(lib)。
然后我们就可以写我们的头文件和cpp源文件了。写完后编译下就可以在目录下找到相应的lib文件了。
在这里我首先写一个相对复杂的库文件,头文件内容是:
- //tv.h
- #ifndef TV_H_
- #define TV_H_
- class Tv
- {
- public:
- friend class Remote; //可以访问Tv类的私有成员
- enum{Off,On};
- enum{MinVal,MaxVal=20};
- enum{Antenna,Cable};
- enum{TV,VCR};
- Tv(int s=Off,int mc=100):state(s),volume(5),maxchannel(mc),channel(2),mode(Cable),input(TV){}
- void onoff(){state=(state==Off)? On:Off;}
- bool ison()const {return state==On;}
- bool volup();
- bool voldown();
- void chanup();
- void chandown();
- void set_mode(){mode=(mode==Antenna)? Cable:Antenna;}
- void set_input(){input=(input==TV)? VCR:TV;}
- void settings()const;
- private:
- int state;
- int volume;
- int maxchannel;
- int channel;
- int mode;
- int input;
- };
- class Remote
- {
- private:
- int mode;
- public:
- Remote(int m=Tv::TV):mode(m){}
- bool volup(Tv &t){return t.volup();}
- bool voldown(Tv &t){return t.voldown();}
- void onoff(Tv &t){t.onoff();}
- void chanup(Tv &t){t.chanup();}
- void chandown(Tv &t){t.chandown();}
- void set_chan(Tv &t,int c){t.channel=c;}
- void set_mode(Tv &t){t.set_mode();}
- void set_input(Tv &t){t.set_input();}
- };
- #endif
源文件是:
- //tv.cpp
- #include <iostream>
- #include "tv.h"
- bool Tv::volup()
- {
- if (volume<MaxVal)
- {
- volume++;
- return true;
- }
- else
- return false;
- }
- bool Tv::voldown()
- {
- if (volume>MinVal)
- {
- volume--;
- return true;
- }
- else
- return false;
- }
- void Tv::chanup()
- {
- if (channel<maxchannel)
- channel++;
- else
- channel=1;
- }
- void Tv::chandown()
- {
- if(channel>1)
- channel--;
- else
- channel=maxchannel;
- }
- void Tv::settings()const
- {
- using std::cout;
- using std::endl;
- cout<<"TV is "<<(state==Off ? "Off":"On")<<endl;
- if (state==On)
- {
- cout<<"Volume setting ="<<volume<<endl;
- cout<<"Channel setting ="<<channel<<endl;
- cout<<"Mode ="<<(mode==Antenna ? "Antenna":"Cable")<<endl;
- cout<<"Input ="<<(input==TV ? "TV":"VCR")<<endl;
- }
- }
编译后即可生成tv.lib(其中tv是项目的名称)。
既然我们生成了自己的库文件,那么我们怎么利用我们的库文件呢?
使用方法跟我们用其他的库文件方法是一样的,都需要三个步骤:
1.包含必要的头文件。 2.链接相应的库文件。 3.使用库文件
比如我在另外一个项目中要使用我刚写的tv.lib库文件,为了方便,我可以把tv.h头文件和tv.lib库文件复制我新建项目的目录下。
然后写如下文件:
- //use_tv.cpp
- #include <iostream>
- #include "tv.h"
- #pragma comment(lib,"tv.lib")
- int main()
- {
- using std::cout;
- Tv s27;
- cout<<"Initial settings for 27\" TV:\n";
- s27.settings();
- s27.onoff();
- s27.chanup();
- cout<<"\nAdjusted settings for 27\" TV:\n";
- s27.settings();
- Remote grey;
- grey.set_chan(s27,10);
- grey.volup(s27);
- grey.volup(s27);
- cout<<"\n27\" settings after using remote:\n";
- s27.settings();
- Tv s32(Tv::On);
- s32.set_mode();
- grey.set_chan(s32,28);
- cout<<"\n32\" settings:\n";
- s32.settings();
- return 0;
- }
输出结果为: