鍍金池/ 問(wèn)答/C  iOS  網(wǎng)絡(luò)安全/ c 語(yǔ)言全局變量的使用

c 語(yǔ)言全局變量的使用

extern 好像能解決這個(gè)問(wèn)題

//main.c
#include <stdio.h>
#include "ggg.h"


int main(int argc, const char * argv[]) {
    ggg();
    return 0;
}
//ggg.h
#ifndef ggg_h
#define ggg_h

#include <stdio.h>

int num;//就是這個(gè)全局變量,好煩
void ggg();

#endif /* ggg_h */
// ggg.c
#include "ggg.h"
void ggg(){
    
    num =1;
    printf("ggg::%d",num);
}
//錯(cuò)誤信息
 duplicate symbol _num in:
/Users/HOHD/Library/Developer/Xcode/DerivedData/testGlobal-dorberrgmwayrsfxpllsxbyhhbud/Build/Intermediates.noindex/testGlobal.build/Debug/testGlobal.build/Objects-normal/x86_64/main.o
/Users/HOHD/Library/Developer/Xcode/DerivedData/testGlobal-dorberrgmwayrsfxpllsxbyhhbud/Build/Intermediates.noindex/testGlobal.build/Debug/testGlobal.build/Objects-normal/x86_64/ggg.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

回答
編輯回答
悶油瓶

如果你希望全局變量能被外部訪問(wèn),就在.h文件里用extern聲明
如果只希望當(dāng)前文件的所有函數(shù)共享這個(gè)全局變量,就在.c文件里聲明

2017年7月16日 08:01
編輯回答
幼梔

這不光是全局變量的問(wèn)題,還涉及到#include的使用效果。編譯器在看到#include時(shí),會(huì)把指定文件中的內(nèi)容完整復(fù)制到本文件中。就你給出的這三個(gè)文件中的內(nèi)容來(lái)講,編譯main.c時(shí),編譯器處理#include "ggg.h"后,main.c文件是這個(gè)樣子:

//main.c
#include <stdio.h>
//ggg.h
#ifndef ggg_h
#define ggg_h

#include <stdio.h>

int num;//就是這個(gè)全局變量,好煩
void ggg();

#endif /* ggg_h */

int main(int argc, const char * argv[]) {
    ggg();
    return 0;
}

也就是說(shuō),int num這個(gè)變量變成了main.c文件的一個(gè)全局變量。
而處理ggg.c文件的時(shí)候,ggg.c將變成下面的樣子:

// ggg.c

//ggg.h
#ifndef ggg_h
#define ggg_h

#include <stdio.h>

int num;//就是這個(gè)全局變量,好煩
void ggg();

#endif /* ggg_h */

void ggg(){
    
    num =1;
    printf("ggg::%d",num);
}

于是ggg.c中也有一個(gè)int num變量。
鏈接這兩個(gè)文件編譯出的目標(biāo)文件的時(shí)候,就出現(xiàn)了兩個(gè)int num,編譯器自然會(huì)報(bào)錯(cuò)了。

2017年12月26日 09:34