一個簡單的makefile樣本及其注釋

來源:互聯網
上載者:User

相信在unix下編程的沒有不知道makefile的,剛開始學習unix平台
下的東西,瞭解了下makefile的製作,覺得有點東西可以記錄下。
  下面是一個極其簡單的例子:
現在我要編譯一個Hello world,需要如下三個檔案:
  1. print.h
      #include<stdio.h>
      void printhello();

  2. print.c
      #include"print.h"
      void printhello(){
        printf("Hello, world/n");
      }

   3. main.c
      #include "print.h"
      int main(void){
        printhello();
        return 0;
      }

  好了,很簡單的程式了。如果我們想要編譯成功需要哪些步驟呢?
我認為在這裡需要理解的就兩步:
  #  為每一個 *.c檔案產生 *o檔案。
  #  串連每一個*o檔案,產生可執行檔。
下面的makefile 就是根據這樣的原則來寫的。

 

一:makefile 雛形:

 


#makefile的撰寫是基於規則的,當然這個規則也是很簡單的,就是:
#target : prerequisites
  command  //任意的shell 命令

執行個體如下:
makefile:
    helloworld : main.o print.o #helloword 就是我們要產生的目標
                 # main.o print.o是產生此目標的先決條件
      gcc -o helloworld main.o print.o#shell命令,最前面的一定是一個tab鍵

    mian.o : mian.c print.h
      gcc -c main.c
    print.o : print.c print.h
      gcc -c print.c
    
    clean :          
        rm helloworld main.o print.o
  OK,一個簡單的makefile製作完畢,現成我們輸入 make,自動調用Gcc編譯了,
輸入 make clean就會刪除 hellowworld mian.o print.o

二:小步改進:



  在上面的例子中我們可以發現 main.o print.o 被定義了多處,
我們是不是可以向C語言中定義一個宏一樣定義它呢?當然可以:
makefile:
    objects =  main.o print.o #應該叫變數的聲明更合適

    helloworld : $(objects) //聲明了變數以後使用就要$()了
      gcc -o helloworld$(objects)
     mian.o : mian.c print.h
      gcc -c main.c
    print.o : print.c print.h
      gcc -c print.c
    
    clean :          
        rm helloworld $(objects)
修改完畢,這樣使用了變數的話在很多檔案的工程中就能體現出方便性了。

三:再進一步:




  再看一下,為沒一個*.o檔案都寫一句gcc -c main.c是不是顯得多餘了,
能不能把它幹掉?而且 main.c 和print.c都需要print.h,為每一個都寫上是
不是多餘了,能不能再改進?
能,當然能了:
makefile:
     objects =  main.o print.o

    helloworld : $(objects)
      gcc -o helloworld$(objects)
    
    $(objects) : print.h # 都依賴print.h
     mian.o : mian.c  #幹掉了gcc -c main.c 讓Gun make自動推導了。
    print.o : print.c     
    clean :          
        rm helloworld $(objects)

好了,一個簡單的makefile就這樣完畢了,簡單吧。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.