【Linux學習】 寫一個簡單的Makefile編譯源碼擷取當前系統時間

來源:互聯網
上載者:User

標籤:style   blog   http   color   strong   檔案   

 

打算學習一下Linux,這兩天先看了一下gcc的簡單用法以及makefile的寫法,今天是周末,天氣悶熱超市,早晨突然發現住處的冰箱可以用了,於是先出去吃了點東西,然後去超市買了一坨冰棍,老冰棍居多,5毛錢一根,還有幾根1.5的。

嗯 接著說gcc的事

先把原始碼貼上來

//gettime.h#ifndef _GET_TIME_H_#define _GET_TIME_H_void PrintCurrentTime();#endif

 

 

 

 

//gettime.c#include <stdio.h>#include <time.h>  //time.h和stdio.h好像要放在前面,否則gcc警示告“ 隱式聲明與內建函數 printf 不相容”之類的#include "gettime.h"void PrintCurrentTime(){    time_t t;    struct tm* a;    time(&t);    a = localtime(&t);    printf("%4d-%02d-%02d %02d:%02d:%02d\n", 1900+a->tm_year, 1 + a->tm_mon,          a->tm_mday, a->tm_hour, a->tm_min, a->tm_sec);}

 

 

 

 

//main1.c#include <stdio.h>#include "gettime.h"int main(){    printf("\n開始列印當前系統時間\n");    PrintCurrentTime();    return 0;}

 

 

 

代碼很簡單,就是擷取當前系統時間並列印出來,然後看Makefile的寫法

      1 OUT = main1.out      2 OBJECTS = main1.o gettime.o      3       4 $(OUT) : $(OBJECTS)      5         gcc -Wall  $^ -o [email protected]      6 main1.o : main1.c      7 gettime.o : gettime.c      8       9 .PHONY: clean     10 clean:     11         rm -f *.o

 

 

這裡用了【變數】【隱晦規則】

變數類似於宏定義,取值時用  $(變數名) 來取, $^ 表示所有依賴檔案, [email protected] 表示當前目標檔案, $< 表示第一個依賴檔案

所謂【隱晦規則】是一種推導模版,也就是“決定怎麼樣從具有副檔名為X的檔案 構造出 另一種副檔名為Y的檔案”;

本例中,main1.o 依賴於main1.c,如果是完整的寫法如下:

gcc -c -Wall  main1.c  -o main1.o

 

類似的,gettime.o依賴於gettime.c 寫為 gcc -c -Wall  gettime.c -o gettime.o

 

怎麼用makefile?

退出makefile編譯,在終端中輸入make命令,即可在目前的目錄中尋找makefile。

 

在make過程中產生的.o的中間檔案怎麼清理呢? 

可以看上面makefile的最後幾行,rm -f *.o 刪除所有尾碼為.o的檔案,在make後,輸入make clean命令即可。

 

另外:

1、makefile可以命名為"makefile" 也可以命名為"Makefile"

2、makefile中命令前要有一個tab鍵,而非空格鍵或其他鍵,怎麼驗證是tab鍵而不是被替換為了空格呢? 在command模式下,移動游標到你認為的tab鍵處,然後按下鍵盤上的字母ga, 在command處如果顯示9則為tab,如果顯示32則為空白格。

 

 

流程以及結果

聯繫我們

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