一.头文件的使用

如果把main函数放在第一个文件中,而把自定义函数放在第二个文件中,那么就需要在第一个文件中声明函数原型。如果把函数原型包含在一个头文件里,那么就不必每次使用函数的时候都声明其原型了。把函数声明放入头文件是很好的习惯。

二.#include 与 #define的意义

#include 是预编译指令,代表头文件包含。#define定义一个宏常量。

三.#ifdef #ifndef与#endif

#ifdef 这是个预编译指令,代表只要定义了一个常量,那么就预编译下面的代码

基本语法:

#ifdef 宏

代码

#endif

#ifndef也是个预编译指令,代表如果这个宏不存在,就编译下面的代码

#ifndef 宏 // 如果这个宏不存在,就编译下面的代码

代码

#endif

四.解决C语言头文件重复包含的问题

比如有一个外部引用的a.h头文件,那么在a.h头文件中应当这样定义:

    #ifndef ____AH____
#define ____AH_____
int mymax(int a, int b); // 声明
int add(int a, int b); // 声明
#endif

实际应用:

下面是在一个C文件中使用另一个C文件中定义的函数并包含其头文件的例子。

test.c

#include <stdio.h> // 这个头文件在系统目录下
#include <stdlib.h> // 使用了system函数
#include "a.h" // 这个头文件在当前目录下 void main() { /*char *a = "hello1234";
printf("当前字符串的长度为:%d\n",mystrlen(a,0));*/ for (int i = ; i < ; i++) {
printf("第%d个数的结果为:%d\n",i,fib(i));
}
system("pause");
}

a.h

#ifndef __AH__
#define __AH__ int mystrlen(const char *p, int n); // 计算当前字符串长度
int fib(int n); // 斐波那契数列
int getBinary(int n); // 将十进制数转换为二进制数
int getAge(int n); // 计算第n个人的年龄
void decreasing(int n); // 先序递归 输出结果:10 9 8 7 6 5 4 3 2 1
void increasing(int n); // 后序递归 输出结果:1 2 3 4 5 6 7 8 9 10 #endif

a.c

#include <stdio.h>

// 计算当前字符串长度
int mystrlen(const char *p, int n) { if (p[n]) { // 这里判断是否到达字符串末尾的0
return mystrlen(p, n + );
}
else {
return n;
} } // 斐波那契数列
int fib(int n) { if (n == )
return ;
if (n == )
return ;
if (n > )
return fib(n - ) + fib(n - ); } //将十进制数转换为二进制数
void getBinary(int n) { int i = n % ;
if (n >= ) {
getBinary(n / );
}
printf("%d", i);
} // 计算第n个人的年龄
int getAge(int n) { int age;
if (n == ) {
age = ;
}
else{
age = getAge(n - ) + ;
}
return age; } // 先序递归 输出结果:10 9 8 7 6 5 4 3 2 1
void decreasing(int n) { if (n > ){ // 递归终止条件,递归一定要有终止条件
printf("n=%d\n", n);
decreasing(n - );
}
} // 后序递归 输出结果:1 2 3 4 5 6 7 8 9 10
void increasing(int n) { if (n > ) {
increasing(n - );
printf("n=%d\n", n);
} }

最新文章

  1. MVC PartialView
  2. [NOIP2012] 提高组 洛谷P1081 开车旅行
  3. sublime text3 快捷键设置
  4. uva 1210
  5. CentOS用yum安装X Window
  6. Android Studio:Gradle常用命令
  7. vb.net写的odbc连接dsn数据源和ole链接oracle的小例子
  8. 关于项目既要使用ant脚本又要使用maven pom.xml文件的问题
  9. LLVM对注释的新增支持 @ WWDC 2013
  10. [ACM] hdu 1671 Phone List (特里)
  11. Java中泛型的理解
  12. xml与json的原理,区别,优缺点.
  13. hdu 5739 割点
  14. Goaccess解析nginx日志备忘
  15. sql server版本、组件和管理工具
  16. linux kernel的cmdline参数解析原理分析【转】
  17. (转)Hashtable与ConcurrentHashMap区别
  18. springboot 整合 redis 共享Session-spring-session-data-redis
  19. npm 包 升降版本
  20. Linux入门基础教程之Linux系统简介

热门文章

  1. 微信小程序开发教程(一)准备
  2. es 数据 导出 到 MySQL
  3. 通过python的logging模块输出日志文件
  4. [OpenJudge8782][划分DP]乘积最大
  5. 每天一个linux命令13之curl发送http请求
  6. SQL Server Wait Types Library
  7. IIS 日志
  8. Microsoft office(1)分页符和分节符
  9. Ueditor .net版安装配置打开项目的源码傻瓜版教程 亲測~
  10. DEDECMS爆严重安全漏洞