文章目录
- 准备文件
- Makefile版本一
- Makefile版本二
- Makefile版本三
- Makefile版本四
- Makefile版本五
准备文件
// fun1.c
#include <stdio.h>
void fun1()
{
printf("this is fun1\n");
}
// fun2.c
#include <stdio.h>
void fun2()
{
printf("this is fun2\n");
}
//head.h
void fun1();
void fun2();
int sum(int len);
//sum.c
#include <stdio.h>
int sum(int len)
{
int i = 0;
int sum = 0;
for(i=0; i<len; i++)
{
sum += i;
}
return sum;
}
//main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include "head.h"
int main(int argc, char *argv[])
{
printf("this is main!\n");
int i = 0;
for(i=0; i<argc; i++)
{
printf("[%d]:[%s]\n", i, argv[i]);
}
fun1();
fun2();
printf("sum(10)==[%d]\n", sum(10));
return 0;
}
Makefile版本一
main: main.c fun1.c fun2.c sum.c
gcc -o main main.c fun1.c fun2.c sum.c
Makefile版本二
main:main.o fun1.o fun2.o sum.o
gcc -o main main.o fun1.o fun2.o sum.o
main.o: main.c
gcc -c main.c -I./
fun1.o: fun1.c
gcc -c fun1.c
fun2.o: fun2.c
gcc -c fun2.c
sum.o: sum.c
gcc -c sum.c
Makefile版本三
target = main
objects = main.o fun1.o fun2.o sum.o
CC = gcc
CPPFLAGS = -I./
#这里的$(objects)不能替换成$^,因为此处是条件,不是命令
$(target): $(objects)
$(CC) -o $@ $^
%.o: %.c
$(CC) -c $< $(CPPFLAGS)
###########################################
#main.o: main.c
# $(CC) -c $< $(CPPFLAGS)
#fun1.o: fun1.c
# $(CC) -c $<
#fun2.o: fun2.c
# $(CC) -c $<
#sum.o: sum.c
# $(CC) -c $<
Makefile版本四
target = main
src = $(wildcard *.c)
objects = $(patsubst %.c, %.o, $(src))
#objects = main.o fun1.o fun2.o sum.o
CC = gcc
CPPFLAGS = -I./
#这里的$(objects)不能替换成$^,因为此处是条件,不是命令
$(target): $(objects)
$(CC) -o $@ $^
%.o: %.c
$(CC) -c $< $(CPPFLAGS)
###########################################
#main.o: main.c
# $(CC) -c $< $(CPPFLAGS)
#fun1.o: fun1.c
# $(CC) -c $<
#fun2.o: fun2.c
# $(CC) -c $<
#sum.o: sum.c
# $(CC) -c $<
Makefile版本五
target = main
src = $(wildcard *.c)
objects = $(patsubst %.c, %.o, $(src))
CC = gcc
CPPFLAGS = -I./
$(target): $(objects)
$(CC) -o $@ $^
%.o: %.c
$(CC) -c $< $(CPPFLAGS)
#clean和前面的命令没有依赖关系
.PHONY: clean
clean:
rm -f $(objects) $(target)