【Linux開發技術之程式構建】Makefile學習(不斷更新)

來源:互聯網
上載者:User

 作者:gnuhpc 
出處:http://www.cnblogs.com/gnuhpc/   

1.入門篇

1)Makefile的作用:協助編譯多檔案。

2)基本編寫樣本:以如下四個檔案為例

//main.c#include"mytool1.h"#include"mytool2.h"int main(int argc,char **argv){mytool1_print("hello");mytool2_print("hello");}//mytool1.h#ifndef _MYTOOL_1_H#define _MYTOOL_1_Hvoid mytool1_print(char *print_str);#endif//mytool1.c#include"mytool1.h"void mytool1_print(char *print_str){printf("This is mytool1 print %s",print_str);}//mytool2.h#ifndef _MYTOOL_2_H#define _MYTOOL_2_Hvoid mytool2_print(char *print_str);#endif//mytool2.c#include"mytool2.h"void mytool2_print(char *print_str){printf("This is mytool2 print %s",print_str);} 

對應進行編譯構建的Makefile為

main:main.o mytool1.o mytool2.ogcc -o main main.o mytool1.o mytool2.omain.o:main.c mytool1.h mytool2.hgcc -c main.cmytool1.o:mytool1.c mytool1.hgcc -c mytool1.cmytool2.o:mytool2.c mytool2.hgcc -c mytool2.c

 

 

Makefile 的本質是參與構建的原始碼之間依賴關係和編譯方法進行說明。一般採用的格式如下:

target: components

TAB rule

第一行表示的是依賴關係.  第二行是規則,使用TAB 鍵進行

main:main.o mytool1.o mytool2.o 就是所謂的依賴關係,實際上是一種庖丁解牛的方式,建議在紙上畫好關係依賴圖,如本例:

main

---main.o--(main.c,mytool1.h,mytool2.h)

|

mytool2.o--(mytool2.c,mytool2.h)

|

mytool1.o--(mytool1.c,mytool1.h)

而gcc -o main main.o mytool1.o mytool2.o 就是所謂的規則。

3)簡化

$@--目標檔案,$^--所有的依賴檔案,$<--第一個依賴檔案,使用替代規則可以簡寫上例如下:

main:main.o mytool1.o mytool2.ogcc -o $@ $^main.o:main.c mytool1.h mytool2.hgcc -c $<mytool1.o:mytool1.cmytool1.hgcc -c $<mytool2.o:mytool2.cmytool2.hgcc -c $<

如果有規律的命名規則,則可以簡寫上例如下:

main:main.o mytool1.o mytool2.ogcc -o $@ $^..c.o:gcc -c $<
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.