Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4733124
  • 博文数量: 930
  • 博客积分: 12070
  • 博客等级: 上将
  • 技术积分: 11448
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-15 16:57
文章分类

全部博文(930)

文章存档

2011年(60)

2010年(220)

2009年(371)

2008年(279)

分类: LINUX

2009-12-28 10:12:30

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[] = " ";
char add2[] = " ";
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[] = " ";

char add2[] = " ";
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 这个文件里不要写定义了,改成声明。注意,对多次全局变量定义的支持只是某些编译器的功能或者特性,而不是必须的。

其实说到底,对编程能力的考核还是在考察编程者的数学能力。
阅读(1183) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~