很多时候,看到很多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 1;
}

 

三、调用部分

/* run.c */
#include "test.h"

int main(int argc, char *argv)
{
    char *ptr = "Hello, world!";
    test_func(ptr);
    return 0;
}

 

四、编译并运行

[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!

相关文章:

  • 2021-12-22
  • 2021-10-01
  • 2021-07-19
  • 2022-12-23
  • 2022-12-23
  • 2021-10-11
  • 2021-12-13
  • 2021-10-28
猜你喜欢
  • 2022-01-12
  • 2022-01-28
  • 2022-12-23
  • 2021-07-18
  • 2023-03-15
相关资源
相似解决方案