免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2706 | 回复: 0
打印 上一主题 下一主题

防止变量重复定义;头文件重复包含、嵌套包含 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-12-28 10:12 |只看该作者 |倒序浏览
test-1.0使用#ifndef只是防止了头文件被重复包含(其实本例中只有一个头件,不会存在重复包含的问题),但是无法防止变量被重复定义。
# vi test.c
-------------------------------
#include
#include "test.h"
extern i;
extern void test1();
extern void test2();
int main()
{
   test1();
   printf("ok
");
   test2();
   printf("%d
",i);
   return 0;
}
# vi test.h
-------------------------------
#ifndef _TEST_H_
#define _TEST_H_
char add1[] = "www.shellbox.cn
";
char add2[] = "www.scriptbox.cn
";
int i = 10;
void test1();
void test2();
#endif
# vi test1.c
-------------------------------
#include
#include "test.h"
extern char add1[];
void test1()
{
   printf(add1);
}
# vi test2.c
-------------------------------
#include
#include "test.h"
extern char add2[];
extern i;
void test2()
{
   printf(add2);
   for (; i > 0; i--)
       printf("%d-", i);
}
# Makefile
-------------------------------
test:    test.o test1.o test2.o
test1.o: test1.c
test2.o: test2.c
clean:
   rm test test.o test1.o test2.o
错误:
test-1.0编译后会出现"multiple definition of"错误。
错误分析:
由于工程中的每个.c文件都是独立的解释的,即使头文件有
#ifndef _TEST_H_
#define _TEST_H_
....
#enfif
在其他文件中只要包含了global.h就会独立的解释,然后每个.c文件生成独立的标示符。在编译器链接时,就会将工程中所有的符号整合在一起,由于文件中有重名变量,于是就出现了重复定义的错误。
解决方法
.c文件中声明变量,然后建一个头文件(.h文件)在所有的变量声明前加上extern,注意这里不要对变量进行的初始化。然后在其他需要使用全局变量的.c文件中包含.h文件。编译器会为.c生成目标文件,然后链接时,如果该.c文件使用了全局变量,链接器就会链接到此.c文件
test-2.0
# vi test.c
-------------------------------
#include
#include "test.h"
int i = 10;
char add1[] = "www.shellbox.cn
";
char add2[] = "www.scriptbox.cn
";
extern void test1();
extern void test2();
int main()
{
   test1();
   printf("ok
");
   test2();
   printf("%d
",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
-------------------------------
#include
#include "test.h"
void test1()
{
   printf(add1);
}
# vi test2.c
-------------------------------
#include
#include "test.h"
void test2()
{
   printf(add2);
   for (; i > 0; i--)
       printf("%d-", i);
}





好的编程习惯也是必须的。在这种情况下,全局变量的定义宜放在某个 .c 文件中,而 .h 文件里写的是变量的声明。你如果不清楚变量应该定义在哪儿,干脆写个 globals.c,然后将变量定义加进去好了。1.h 这个文件里不要写定义了,改成声明。注意,对多次全局变量定义的支持只是某些编译器的功能或者特性,而不是必须的。
其实说到底,对编程能力的考核还是在考察编程者的数学能力。


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/76292/showart_2132548.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP