main.c
#include <stdio.h>
#include <sys/types.h>
#include "hello.h"
int main(void)
{
hello();
here();
bye();
exit(0);
}
hello.h
void hello();
void here();
void bye();
hello.c
#include <stdio.h>
void hello()
{
printf("Hello!\n");
}
here.c
#include <stdio.h>
void here()
{
printf("I'm here\n");
}
bye.c
#include <stdio.h>
void bye()
{
printf("Goodbye!\n");
}
Makefile
CC = gcc
PROG = myhello
HRDS = hello.h
SRCS = main.c hello.c here.c bye.c
CFLAG = -g -Wall
OBJS = $(SRCS:*.c=*.o)
$(PROG) : $(OBJS)
$(CC) $(OBJS) -o $(PROG)
main.o : main.c hello.h
hello.o : hello.c
here.o : here.c
bye.o : bye.c
clean:
rm -f $(OBJS)
运行结果

Makefile还有另一种写法
main:main.o hello.o here.o bye.o
main.o:main.c
gcc -c main.c -o main.o
hello.o:hello.c
gcc -c hello.c -o hello.o
here.o:here.c
gcc -c here.c -o here.o
bye.o:bye.c
gcc -c bye.c -o bye.o
.PHONY:clean
clean:
-rm -rf *.o
运行结果:

注意!在Makefile里,缩进是Tab键实现的,否则会报错“*** missing separator. Stop.”

本文介绍了一个使用C语言进行模块化编程的例子,包括main.c作为主文件调用hello.c、here.c和bye.c三个独立模块,以及如何通过Makefile进行自动化构建和清理。展示了C语言函数声明与定义的分离,以及Makefile中目标和依赖关系的设置。

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



