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声明
如果只希望当前文件的所有函数共享这个全局变量,就在.c文件里声明