C语言 .h之间参数相互调用
这看似是个简单的问题,但也很容易产生知识误区。
1. 举例新建几个.h 文件
a.h
#ifndef _A_H_
#define _A_H_
//头文件内容。
typedef struct {
int len;
}str_A;
#endif
b.h
#ifndef _B_H_
#define _B_H_
#include "e.h" //参数的.h里 调用其e.h时注意不能直接或间接调用d.h 否则d.h会报参数错误
//头文件内容。
typedef struct {
int len;
}str_B;
#endif
c.h
#ifndef _C_H_
#define _C_H_
#include "a.h" // a.h没有直接或间接调用c.h 所以可以引用str_A 参数
//头文件内容。
int func(str_A str_a); //**不会报参数引用错误**
#endif
d.h
#ifndef _D_H_
#define _D_H_
#include "b.h" //
//头文件内容。
int funestr_B str_b); //**会报错误:**因为b.h里简介调用了d.h
#endif
e.h
#ifndef _E_H_
#define _E_H_
#include "d.h"
//头文件内容。
#endif
- #ifndef A_H#define _A_H_作用
一个头文件被引用两次,编译器会处理两次头文件的内容,会 产生错误。这样可以避免重复包含。
3. .h之间的参数相互调用
c.h调用a.h的参数是正确的
因为c.h编译 int func(str_A str_a)时会先编译 #include “a.h”
d.h调用b.h的参数可能会出错
因为b.h通过调用e.h 间接调用了d.h 因此预编译时 d.h调用b.h的参数会报错
所以 .h之间参数相互调用时注意:
被调用的参数的a.h被其他函数调用时
a.h里尽量不要有其他.h函数,因为其他的.h函数很有可能会调用此.h,导致此.h调用参数时导致找不到参数