05.如何編寫自己的h檔案和c檔案,並按專案管理多個源檔案-Make

來源:互聯網
上載者:User

我們在編寫的程式的時候,為了複用會封裝一些方法,這樣就涉及到多個檔案的編譯,如何編譯這些不同的檔案,並連結成最後的可執行程式,如何管理這些檔案,一次編譯?

編寫math.h 標頭檔

/*--===------------------------------------------===---
filename: math.h
實現簡單的檔案操作
--===------------------------------------------===---*/
extern int add(int i, int j);

 
編寫math.c檔案

/*--===------------------------------------------===---
filename: math.c
實現 math.h 檔案裡面定義的方法
編譯方法:gcc -c math.c -o math.o
--===------------------------------------------===---*/
int add(int i, int j)
{
        return i+j;
}

編寫main.c程式

/*--===------------------------------------------===---
filename: main.c
主程式,測試 math.h 和 math.c 檔案。
編譯方法:gcc -c main.c -o main.o
--===------------------------------------------===---*/
#include "math.h"
#include <stdio.h>
int main(int argc, int argv)
{
        printf("the sum 3+5=%d.\n",add(3,5));
        return 0;
}

最後,通過 gcc main.o math.o -o main 產生main程式。

xumh@ubuntu:~/cpp/make$ cat makefile
main: main.o math.o
gcc main.o math.o -o main

main.o : main.c math.h
gcc -c main.c -o main.o

math.o : math.c math.h
gcc -c math.c -o math.o

clean:
rm -f *.o
xumh@ubuntu:~/cpp/make$

 

聯繫我們

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