Fork me on GitHub

C语言头文件源文件

C语言头文件源文件

1、头文件与源文件

头文件用于声明接口函数,格式如下

如创建test.h

#ifndef _TEST_H_
#define _TEST_H_

/*接口函数的申明*/

#endif
#ifndef _TEST_H_
#define _TEST_H

int sum(int x, int y);

void swap(int *x, int *y);

int max(int x, int y);

#endif

 

源文件用于接口函数的实现,源文件中只写接口函数的实现不能写main()函数

#include <stdio.h>
#include "test.h"

int sum(int x, int y)
{
    return x+y;
}

void swap(int *x, int *y)
{
    int tmp;
    tmp = *x;
    *x = *y;
    *y = tmp;
}

int max(int x, int y)
{
    return (x>y)? x : y;
}

 

2、用户文件

头文件和源文件一般是标准库文件或者自定义的库文件,用户文件则是我们自己写的文件,我们需要在用户文件中使用库文件或函数,就要包含所需的头文件

#include <stdio.h>
#include "test.h"

int main()
{
    int a = 1, b = 2;

    swap(&a, &b);

    printf("sum(%d,%d)=%d\n", a, b, sum(a, b));
    printf("a=%d, b=%d\n", a, b);
    printf("max(%d,%d)=%d\n", a, b, max(a, b));

    return 0;
}

 

3、多文件编译

当我们使用的时候,如果只编译main.c(gcc main.c)就会报错

 

 

 原因是在test.h中找不到函数的实现,所以在编译时要将源文件test.c和main.c一起编译(gcc main.c test.c),这样就不会报错

 

4、makefile和shell脚本

当我们包含的头文件特别多,在编译时就要编译很多源文件(gcc main.c test1.c test2.c test3.c test4.c ... testn.c) ,这样就会非常长,所以我们可以将命令行写到脚本里面进行批处理

(1)shell脚本

创建一个build.sh的脚本文件,然后将需要编译的命令行写到脚本文件里,编译时输入命令 sh build.sh就完成了编译

 

 

 

 

(2)makefile

 

(待续。。。)

posted @ 2020-09-01 21:12  小黑子杜  阅读(1170)  评论(0编辑  收藏  举报