DSP

DSP .c 和.h文件架构

2019-07-13 09:41发布

test.c文件构架 1、包含本文件对应头文件test.h 2、定义仅供本文件内部使用全局变量:用static修饰 3、定义可供外部文件使用的全局变量 4、引用外部文件定义的全局变量的申明:加extern 5、为本文件内定义的函数分配存储空间
test.h文件架构 1、条件编译,以防头文件被重复包含 #ifndef _TEST_H_  #define _TEST_H_ ----- #endif 2、包含test.c用到的头文件 3、test.c用到的enum和struct类型的typedef申明 4、test.c用到的外部文件定义的函数原型声明:用extern修饰

实例说明上述文件结构下各个.c文件直接怎么传递数据: 以main.c fun1.c fun2.c为例,fun2.c想获取fun1.c里面global_fun1本地变量的值,由于global_fun1为fun1.c的静态变量,fun2.c无法直接访问。要想获取fun1.c有两种方法: 方法1:在fun1.c中定义一个返回值为指针的函数。通过fun2.c调用fun1.c这个函数,得到global_fun1变量的地址,通过该地址访问。 方法2:在fun1.c中定义一个传入指针变量的函数。通过fun2.c调用fun1.c这个函数,将fun2.c的本地变量地址传递至fun1.c,在fun1.c里面将传过来的地址进行赋值。 两者main函数无改动,主要是fun1.c有改动。通过此例可以说明,在C语言中变量名有自己的作用域限制,但地址的作用域是全局的。
注意:如果在函数内部,定义指针变量(栈空间)但未进行初始化,或初始化有问题。编译的时候不会报错,运行的时候会报。 例如: #include"fun3.h"
static int global_fun2;
void fun2()
{
int *p;
get_global_fun1(p);

printf("--global_fun1--is--%d-- ",global_fun2);
} @ubuntu:~/les3$ ./main.out
Segmentation fault (core dumped)


方法1代码: main.h #ifndef _main_h
#define _main_h
#include"fun1.h"
#include"fun2.h"
#endif
main.c #include"fun1.h"
#include"fun2.h"
void main()
{
fun2();
} fun2.h #ifndef _fun2_h
#define _fun2_h
#include"fun1.h"
#include"stdio.h"
extern void fun2();
#endif
fun2.c #include"fun2.h"
static int global_fun2;
void fun2()
{
int *p_data=0;
p_data=get_global_fun1();
printf("--global_fun1--is--%d-- ",*p_data);
}
fun1.h #ifndef _fun1_h
#define _fun1_h
extern int* get_global_fun1();
#endif
fun1.c static int global_fun1 = 10086;
int* get_global_fun1()
{
return &global_fun1;
}
输出结果 @ubuntu:~/les2$ ./main.out
--global_fun1--is--10086--

方法二代码: main.h #ifndef _main_h
#define _main_h
#include"fun1.h"
#include"fun2.h"
#endif
main.c #include"fun1.h"
#include"fun2.h"
void main()
{
fun2();
} fun2.h #ifndef _fun2_h
#define _fun2_h
#include"fun1.h"
#include"stdio.h"
extern void fun2();
#endif
fun2.c #include"fun2.h"
static int global_fun2;
void fun2()
{
get_global_fun1(&global_fun2);
printf("--global_fun1--is--%d-- ",global_fun2);
} fun1.h #ifndef _fun1_h
#define _fun1_h
extern void get_global_fun1();
#endif
fun1.c static int global_fun1 = 10086;
void get_global_fun1(int *p)
{
 *p = global_fun1;
}
输出结果: @ubuntu:~/les3$ ./main.out
--global_fun1--is--10086--