Makefile简单试验

 编写两个简单的文件,用Makefile来让他们自动编译连接。
 


  • main函数

    #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_H
     void mytool1_print(char *print_str);
    #endif

  • mytool1.c

    #include “mytool1.h”
    void mytool1_print(char *print_str)
    {
     printf(“This is mytool1 print %s\n”,print_str);
    }

  • mytool2.h

    #ifndef _MYTOOL_2_H
    #define _MYTOOL_2_H
     void mytool2_print(char *print_str);
    #endif

  • mytool2.c

    #include “mytool2.h”
    void mytool2_print(char *print_str)
    {
     printf(“This is mytool2 print %s\n”,print_str);
    }

  • Makefile

    main:main.o mytool1.o mytool2.o
      gcc -o main main.o mytool1.o mytool2.o
    main.o:main.c mytool1.h mytool2.h
      gcc -c main.c
    mytool1.o:mytool1.c mytool1.h
      gcc -c mytool1.c
    mytool2.o:mytool2.c mytool2.h
      gcc -c mytool2.c

    注意 这里gcc前面的必须是tab 缩进。


将源文件和makefile一起放在linux下的同一个文件夹下就可以进行编译了。

[david@localhost 1c]$  make
[david@localhost 1c]$ ./main
This is mytool1 print hello
This is mytool2 print hello

makefile是没有后缀的。

  1. 在上面的例子中,make命令首先会在当前目录下找名字叫“makefile”或“Makefile”的文件。
  2. 如果 找到就会去找这个文件中的第一个目标文件(target),这个例子中是main是本次的最终目标文件。
  3. 如果main文件不存在,或是main依赖后面的.o 文件的文件修改时间比这个文件新,那么它就会执行后面所定义的命令来生成main这个文件。
  4. 如果main依赖的.o 文件不存在,make会在当前文件中找目标为.o 文件的依赖性,如果找到则再根据那一个规则生成.o 文件。和递归差不多~~
  5. 如果c和h文件存在,就会make生成.o 文件,然后.o 再生成执行文件main 。

    大概就是这样,一层一层去找文件的依赖关系,知道最终编译成功。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值