雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C語言

當(dāng)前位置:主頁 > 軟件編程 > C語言 >

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

來源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C語言|點(diǎn)擊:

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

復(fù)制代碼 代碼如下:

# 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);
}


復(fù)制代碼 代碼如下:

# 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

錯(cuò)誤:
test-1.0編譯后會(huì)出現(xiàn)"multiple definition of"錯(cuò)誤。

錯(cuò)誤分析:
由于工程中的每個(gè).c文件都是獨(dú)立的解釋的,即使頭文件有
#ifndef _TEST_H_
#define _TEST_H_
....
#enfif
在其他文件中只要包含了global.h就會(huì)獨(dú)立的解釋,然后每個(gè).c文件生成獨(dú)立的標(biāo)示符。在編譯器鏈接時(shí),就會(huì)將工程中所有的符號(hào)整合在一起,由于文件中有重名變量,于是就出現(xiàn)了重復(fù)定義的錯(cuò)誤。

解決方法
在.c文件中聲明變量,然后建一個(gè)頭文件(.h文件)在所有的變量聲明前加上extern,注意這里不要對變量進(jìn)行的初始化。然后在其他需要使用全局變量的.c文件中包含.h文件。編譯器會(huì)為.c生成目標(biāo)文件,然后鏈接時(shí),如果該.c文件使用了全局變量,鏈接器就會(huì)鏈接到此.c文件 。

test-2.0

復(fù)制代碼 代碼如下:

# 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);
}


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

上一篇:bloom filter概念講解以及代碼分析

欄    目:C語言

下一篇:內(nèi)聯(lián)函數(shù)inline與宏定義深入解析

本文標(biāo)題:頭文件不宜定義變量的原因全面解析

本文地址:http://www.jygsgssxh.com/a1/Cyuyan/4115.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有