自己觉得经常用到的防止编译器报错的方法
1、防止一个头文件被重复包含
#ifndef _ABC_H
#define _ABC_H
头文件的内容
#endif
这个经常用到
2、防止变量被重复定义
在.c文件中定义变量(可以初始化),然后建一个头文件(.h文件)在所有的变量声明前加上 extern,注意这里不要对变量进行的初始化。然后在其他需要使用全局变量的.c文件中包含.h文件。编译器会为.c生成目标文件,然后链接时,如果该.c文件使用了全局变量,链接器就会链接到.c文件。
# vi test.c
-------------------------------
#i nclude <stdio.h>
#i nclude "test.h"
int i = 10;
char add1[] = "www.shellbox.cn\n";
char add2[] = "www.box.cn\n";
extern void test1();
extern void test2();
int main()
{
test1();
printf("ok\n");
test2();
printf("%d\n",i);
return 0;
}
# vi test.h
-------------------------------
#ifndef _TEST_H_
#define _TEST_H_
extern i;
extern char add1[];
extern char add2[];
void test1();
void test2();
#endif
# vi test1.c
-------------------------------
#i nclude <stdio.h>
#i nclude "test.h"
void test1()
{
printf(add1);
}
# vi test2.c
-------------------------------
#i nclude <stdio.h>
#i nclude "test.h"
void test2()
{
printf(add2);
for (; i > 0; i--)
printf("%d-", i);
}
文章评论(0条评论)
登录后参与讨论