在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

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

c 語言全局變量的使用

extern 好像能解決這個問題

//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;//就是這個全局變量,好煩
void ggg();

#endif /* ggg_h */
// ggg.c
#include "ggg.h"
void ggg(){
    
    num =1;
    printf("ggg::%d",num);
}
//錯誤信息
 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)

回答
編輯回答
悶油瓶

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

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

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

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

#include <stdio.h>

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

#endif /* ggg_h */

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

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

// ggg.c

//ggg.h
#ifndef ggg_h
#define ggg_h

#include <stdio.h>

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

#endif /* ggg_h */

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

于是ggg.c中也有一個int num變量。
鏈接這兩個文件編譯出的目標文件的時候,就出現(xiàn)了兩個int num,編譯器自然會報錯了。

2017年12月26日 09:34