makefile学习经验(一)----初涉makefile

一.我对makefile的理解:

经过一段时间对makefile的学习,我理解的makefile就是将程序员手动编译源文件的过程用一个脚本执行,这对于小型项目来说,程序员手动执行和用makefile来执行感官上可能没有大的差异,但是对于中大型项目来说,makefile的存在大大提供了程序员编译代码效率,一个好的makefile文件是一个项目健康存在的基础。

 

二.初涉makefile:

   用个简单的例子初步认识下makefile:

源文件:test.cpp:

#include<iostream>

using namespace std;

 

class A

{

        private:

        int a;

        public:

        A(int i)

        {

                a=i;

        }

 

        void disp()

        {

                cout<<a<<",";

        }

};

 

class B

{

        private:

        int b;

        public:

        B(int j)

        {

                b=j;

        }

 

        void disp()

        {

                cout<<b<<",";

        }

};

 

class C:public B,public A

{

        private:

        int c;

        public:

        C(int k):

        A(k-2),B(k+2)

        {  

                c=k;

        }

 

        void disp()

        {

                A::disp();

                B::disp();

                cout<<c<<endl;

        }

};

 

int main()

{

        C obj(10);

        obj.disp();

        return 0;

}

 

Makefile文件Makefile:

test:test.o

        g++  test.o  -o  test   

test.o:test.cpp

        g++  -c  test.cpp  -o  test.o

 

clean:

        rm  -fr  test  test.o

****************************************************************************

test:test.o                         ---- test是目标文件,也就是最后要生成的可执行文件;

                                               test.o编译源文件产生的中间代码文件;

                                               这行命令的意思是:目标文件test的产生依赖于中间代码文件test.o;

g++  test.o  -o  test           ---- 这行是编译器通过中间代码文件产生目标文件的命令,命令必须以tab键打头,否则执行的时候会报错;这边使用的是g++编

                                               译器,所以你的环境必须安装g++编译器;

test.o:test.cpp                    ----这行的目标文件是test.o,依赖文件是test.cpp;和第一行的格式相同;

g++ -c test.cpp –o test.o     ----这行是通过源文件test.cpp如何生成中间代码文件test.o,是编译命令;

 

clean:

        rm  -fr  test  test.o

 

clean是清除想要删除的文件,执行的时候需要使用命令make clean,一般是删除中间代码文件和最后生成的目标文件,即可执行文件;

 

      在环境中执行make命令,系统就会在目录下自动寻找Makefile、makefile文件,然后执行makefile文件中的内容;同样,你可以指定你自己的makefile文件名,比如:makefile_201020831,执行的时候必须用make –f makefile_201020831;

      Makefile的执行过程是一个递归的过程,目标文件:依赖文件,是使用命令通过依赖文件生成目标文件的过程;

      验证生成的目标文件,即可执行文件,直接./test即可。

posted on 2012-08-31 13:45  Kimi_jun  阅读(1933)  评论(0编辑  收藏  举报

导航