首页 > 编程语言 > 详细

C语言 多文件编程

时间:2020-02-27 20:05:46      阅读:68      评论:0      收藏:0      [点我收藏+]

C语言 多文件编程

分文件编程

  • 把函数声明放在头文件xxx.h中,在主函数中包含相应头文件
  • 在头文件对应的xxx.c中实现xxx.h声明的函数

防止头文件重复包含

1、当一个项目比较大时,往往都是分文件,这时候有可能不小心把同一个头文件 include 多次,或者头文件嵌套包含。

a.h 中包含 b.h :

#include "b.h"

b.h 中包含 a.h:

#include "a.h"

main.c 中使用其中头文件:

#include "a.h"

int main()
{
return 0;
}

2、为了避免同一个文件被include多次,C/C++中有两种方式,一种是 #ifndef 方式,一种是 #pragma once 方式。

方法一:

#ifndef __SOMEFILE_H__
#define __SOMEFILE_H__

// 声明语句
#endif

方法二:

#pragma once

案例

文件1:01main.c

#include <stdio.h>
#include "02fun.h"

int main(void)
{
    int a = 10;
    int b = 20;
    printf("%d\n",max(a, b));
}

文件2:02fun.c

// 函数定义
int max(int a, int b)
{
    return a > b ? a : b;
}

文件3:02fun.h

// 防止头文件重复包含
// 方法一
// 只能用于 windos
#pragma once 
// 方法二 Linux、Windos
// #ifndef __02_FUN_H__
// #define __02_FUN_H__

// 全局变量的定义
// 函数的声明
extern int max(int a, int b);

 

C语言 多文件编程

原文:https://www.cnblogs.com/xiangsikai/p/12373974.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!