很多时候,看到很多c函数的声明和实现是分开的。声明放在头文件,实现却放在另一个文件,最后函数被其他文件调用。
下面以简单例子说明。
一、声明部分
/* test.h */
#include <stdio.h> int test_func(char *ptr); /* 声明函数 */
二、实现部分
/* test.c */
#include "test.h" int test_func(char *ptr) /* 实现函数 */
{
printf("%s\n", ptr);
return ;
}
三、调用部分
/* run.c */
#include "test.h" int main(int argc, char *argv)
{
char *ptr = "Hello, world!";
test_func(ptr);
return ;
}
四、编译并运行
[zzb@localhost test]$ ls
run.c test.c test.h
[zzb@localhost test]$ gcc test.c -c
[zzb@localhost test]$ ls
run.c test.c test.h test.o
[zzb@localhost test]$ gcc test.o run.c -o run
[zzb@localhost test]$ ls
run run.c test.c test.h test.o
[zzb@localhost test]$ ./run
Hello, world!
最后编译记得把实现函数体部分test.o加进到run.c!