许明会的计算机技术主页

Language:C,C++,.NET Framework(C#)
Thinking:Design Pattern,Algorithm,WPF,Windows Internals
Database:SQLServer,Oracle,MySQL,PostSQL
IT:MCITP,Exchange,Lync,Virtualization,CCNP

导航

05.如何编写自己的h文件和c文件,并按项目管理多个源文件-Make

我们在编写的程序的时候,为了复用会封装一些方法,这样就涉及到多个文件的编译,如何编译这些不同的文件,并链接成最后的可执行程序,如何管理这些文件,一次编译?

编写math.h 头文件

/*--===------------------------------------------===---
filename: math.h
实现简单的文件操作
--===------------------------------------------===---
*/
extern int add(int i, int j);

 
编写math.c文件

/*--===------------------------------------------===---
filename: math.c
实现 math.h 文件里面定义的方法
编译方法:gcc -c math.c -o math.o
--===------------------------------------------===---
*/
int add(int i, int j)
{
        
return i+j;
}


编写main.c程序

/*--===------------------------------------------===---
filename: main.c
主程序,测试 math.h 和 math.c 文件。
编译方法:gcc -c main.c -o main.o
--===------------------------------------------===---
*/
#include 
"math.h"
#include 
<stdio.h>
int main(int argc, int argv)
{
        printf(
"the sum 3+5=%d.\n",add(3,5));
        
return 0;
}

最后,通过 gcc main.o math.o -o main 生成main程序。

xumh@ubuntu:~/cpp/make$ cat makefile
main: main.o math.o
gcc main.o math.o -o main

main.o : main.c math.h
gcc -c main.c -o main.o

math.o : math.c math.h
gcc -c math.c -o math.o

clean:
rm -f *.o
xumh@ubuntu:~/cpp/make$

 

posted on 2008-11-05 17:21  许明会  阅读(1432)  评论(0编辑  收藏  举报