国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C > 正文

頭文件不宜定義變量的原因全面解析

2020-01-26 15:51:42
字體:
來源:轉載
供稿:網友

test-1.0使用#ifndef只是防止了頭文件被重復包含(其實本例中只有一個頭件,不會存在重復包含的問題),但是無法防止變量被重復定義。

復制代碼 代碼如下:

# vi test.c
-------------------------------
#include <stdio.h>
#include "test.h"

extern i;
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_

char add1[] = "www.shellbox.cn/n";
char add2[] = "www.scriptbox.cn/n";
int i = 10;
void test1();
void test2();

#endif

# vi test1.c
-------------------------------
#include <stdio.h>
#include "test.h"

extern char add1[];

void test1()
{
   printf(add1);
}

# vi test2.c
-------------------------------
#include <stdio.h>
#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 <stdio.h>
#include "test.h"

int i = 10;
char add1[] = "www.shellbox.cn/n";
char add2[] = "www.scriptbox.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
-------------------------------
#include <stdio.h>
#include "test.h"

void test1()
{
   printf(add1);
}

# vi test2.c
-------------------------------
#include <stdio.h>
#include "test.h"

void test2()
{
   printf(add2);
   for (; i > 0; i--)
       printf("%d-", i);
}


個人認為解決此類問題有幾種辦法:
1.在.cpp里定義變量,在其他調用處使用extern
2.在頭文件里使用宏定義

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 安仁县| 图们市| 南澳县| 高碑店市| 广元市| 朝阳县| 鸡泽县| 仁怀市| 兴海县| 临安市| 绥棱县| 申扎县| 离岛区| 乌什县| 吴堡县| 留坝县| 桐庐县| 麟游县| 冕宁县| 缙云县| 淮北市| 类乌齐县| 响水县| 都兰县| 吐鲁番市| 普定县| 新余市| 黄骅市| 柯坪县| 涡阳县| 曲阜市| 柳江县| 仁寿县| 孝昌县| 平江县| 白山市| 利川市| 康平县| 昭通市| 三江| 无为县|