歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux下C編程裡的makefile

Linux下C編程裡的makefile

日期:2017/3/1 10:20:10   编辑:Linux編程

假設我們有下面這樣的程序:

  1. /*main.c*/
  2. #include "mytool1.h"
  3. #include "mytool2.h"
  4. #include <stdio.h>
  5. int main(int argc,char *argv[])
  6. {
  7. mytool1_print("hello");
  8. mytool2_print("hello");
  9. }
  10. /*mytoo1.h*/
  11. #ifndef _MYTOOL1_H
  12. #define _MYTOOL1_H
  13. void mytool1_print(char *print_str);
  14. #endif
  15. /*mytool1.c*/
  16. #include "mytool1.h"
  17. void mytool1_print(char *print_str)
  18. {
  19. printf("This is mytool1 print %s\n",print_str);
  20. }
  21. /*mytool2.h*/
  22. #ifndef _MYTOOL2_H
  23. #define _MYTOOL2_H
  24. void mytool2_print(char *print_str);
  25. #endif
  26. /*mytool2.c*/
  27. #include "mytool2.h"
  28. void mytool2_print(char *print_str)
  29. {
  30. printf("This is mytool2 print %s\n",print_str);
  31. }

我們可以這麼編譯鏈接這個程序:

gcc -c main.c

gcc -c mytool1.c

gcc -c mytool2.c

gcc -o myprint main.o mytool1.o mytool2.o

這樣之後只需執行命令"./myprint",便可以簡單的運行這個程序。

但是當我們修改了其中的一個文件之後是不是還要不厭其煩的輸入上面的編譯命令?

為了解決這一問題,我們有個好方法去解決,那就是編寫一個makefile文件,用make命令去編譯上面的程序。

執行命令"vim Makefile”

編寫如下代碼:

  1. main: main.o mytool1.o mytool2.o
  2. [Tab]gcc -o myprint main.o mytool1.o mytool2.o
  3. main.o: main.c mytool1.h mytool2.h
  4. [Tab]gcc -c main.c
  5. mytool1.o: mytool1.c mytool1.h
  6. [Tab]gcc -c mytool1.c
  7. mytool2.o: mytool2.c mytool2.h
  8. [Tab]gcc -c mytool2.c

保存後執行命令“make -f Makefile”

這樣也可以生成一個可執行程序。

Copyright © Linux教程網 All Rights Reserved