C语言中头文件包含时变量重定义

上传人:平*** 文档编号:14309971 上传时间:2017-10-29 格式:DOCX 页数:4 大小:16.71KB
返回 下载 相关 举报
C语言中头文件包含时变量重定义_第1页
第1页 / 共4页
C语言中头文件包含时变量重定义_第2页
第2页 / 共4页
C语言中头文件包含时变量重定义_第3页
第3页 / 共4页
C语言中头文件包含时变量重定义_第4页
第4页 / 共4页
亲,该文档总共4页,全部预览完了,如果喜欢就下载吧!
资源描述

《C语言中头文件包含时变量重定义》由会员分享,可在线阅读,更多相关《C语言中头文件包含时变量重定义(4页珍藏版)》请在金锄头文库上搜索。

1、防止变量重复定义;头文件重复包含、嵌套包含test-1.0 使用#ifndef 只是防止了头文件被重复包含 (其实本例中只有一个头件,不会存在重复包含的问题),但是无法防止变量被重复定义。# vi test.c-#include #include test.hextern i;extern void test1();extern void test2();int main()test1();printf(okn);test2();printf(%dn,i);return 0;# vi test.h-#ifndef _TEST_H_#define _TEST_H_char add1 = n;ch

2、ar add2 = n;int i = 10;void test1();void test2();#endif# vi test1.c-#include #include test.hextern char add1;void test1()printf(add1);# vi test2.c-#include #include test.hextern char add2;extern i;void test2()printf(add2);for (; i 0; i-) printf(%d-, i);# Makefile-test: test.o test1.o test2.otest1.o:

3、 test1.ctest2.o: test2.cclean: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

4、文件)在所有的变量声明前加上 extern,注意这里不要对变量进行的初始化。然后在其他需要使用全局变量的.c 文件中包含.h 文件。编译器会为.c 生成目标文件,然后链接时,如果该.c 文件使用了全局变量,链接器就会链接到此.c 文件 。test-2.0# vi test.c-#include #include test.hint i = 10;char add1 = n;char add2 = n;extern void test1();extern void test2();int main()test1();printf(okn);test2();printf(%dn,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.hvoid test1()printf(add1);# vi test2.c-#include #include test.hvoid test2()printf(add2);for (; i 0; i-) printf(%d-, i);引用自:http:/

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 行业资料 > 其它行业文档

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号