首先我们给定三个文件:main_plus.c, plus.c plus.h
main_plus.c
/*************************************************************************
> File Name: main_plus.c
> Author: ahuang1900
> Mail: ahuang1900@qq.com
> Created Time: 2014年10月04日 星期六 20时27分53秒
************************************************************************/
#include<stdio.h>
#include "plus.h"
int main(void)
{
int a = 0, b = 0;
printf("Please enter integer a:");
scanf("%d",&a);
printf("\nPlease enter integer b:");
scanf("%d",&b);
if ( a>b) {
printf("\nThe sum is %d\n", plus(b,a));
} else {
printf("\nThe sum is %d\n", plus(a,b));
}
return 0;
}
plus.c
/*************************************************************************
> File Name: plus.c
> Author: ahuang1900
> Mail: ahuang1900@qq.com
> Created Time: 2014年10月04日 星期六 20时34分18秒
************************************************************************/
#include<stdio.h>
#include "plus.h"
int plus(int a, int b)
{
int sum = a;
int i;
for (i = a+1; i<=b; i++)
sum += i;
return sum;
}
plus.h
/*************************************************************************
> File Name: plus.h
> Author: ahuang1900
> Mail: ahuang1900@qq.com
> Created Time: 2014年10月04日 星期六 20时32分02秒
************************************************************************/
#ifndef _PLUS_H_
#define _PLUS_H_
#include <stdio.h>
int plus(int a, int b);
#endif
如果不编写makefile,通常我们的做法是:
hellen@hellen1900:~/myjob/makefile$ ls
main_plus.c makefile plus.c plus.h
hellen@hellen1900:~/myjob/makefile$ gcc -c main_plus.c
hellen@hellen1900:~/myjob/makefile$ gcc -c plus.c
hellen@hellen1900:~/myjob/makefile$ ls
main_plus.c main_plus.o makefile plus.c plus.h plus.o
hellen@hellen1900:~/myjob/makefile$ gcc -o main plus.o main_plus.ohellen@hellen1900:~/myjob/makefile$ ls
main main_plus.c main_plus.o makefile plus.c plus.h plus.o
hellen@hellen1900:~/myjob/makefile$ ./main
Please enter integer a:1
Please enter integer b:2
The sum is 3
hellen@hellen1900:~/myjob/makefile$
因此我们可以编写makefile如下:
版本1:
main: main_plus.o plus.o
gcc -o main main_plus.o plus.o
main_plus.o: main_plus.c plus.h
gcc -c main_plus.c
plus.o: plus.c plus.h
clean:
rm -f *.o main
版本2:
#$@:目标文件
#$^:所有的依赖文件
#$<:第一个依赖文件
main:main_plus.o plus.o
gcc -o $@ $^
main_plus.o: main_plus.c plus.h
gcc -c $<
plus.o: plus.c plus.h
gcc -c $<
clean:
rm -f *.o main
版本3:
object = main_plus.o plus.o
main: $(object)
gcc -o $@ $(object)
main_plus.o: main_plus.c
plus.o: plus.c
clean:
rm -f *.o main
版本4:
CC=gcc
CFLAG = -g -Wall
object = main_plus.o plus.o
main : $(object)
$(CC) $(CFLAG) -o $@ $^
main_plus.o : main_plus.c
plus.o : plus.c
%.o:%c
$(CC) $(CFLAG) -c -o $@ $<
clean:
rm -f *.o main
参考:http://blog.csdn.net/xj626852095/article/details/37879217
本文介绍了一个简单的Makefile实例,通过三个文件(main_plus.c、plus.c、plus.h)的编译过程,展示了如何使用Makefile简化C语言项目的编译工作。文章提供了四个不同版本的Makefile,从基础到高级逐步深入。

6178

被折叠的 条评论
为什么被折叠?



