The use of global variables in C language

extern seems to solve this problem

//main.c
-sharpinclude <stdio.h>
-sharpinclude "ggg.h"


int main(int argc, const char * argv[]) {
    ggg();
    return 0;
}
//ggg.h
-sharpifndef ggg_h
-sharpdefine ggg_h

-sharpinclude <stdio.h>

int num;//
void ggg();

-sharpendif /* ggg_h */
// ggg.c
-sharpinclude "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)

Apr.05,2021

if you want the global variable to be accessed externally, declare
in the .h file with extern > if you only want all functions in the current file to share the global variable, declare


in the .c file.

this is not only a problem of global variables, but also involves the use of -sharpinclude . When the compiler sees -sharpinclude , it copies the contents of the specified file completely into this file. In terms of the contents of the three files you give, when compiling main.c , after the compiler processes -sharpinclude "ggg.h" , the main.c file looks like this:

// ggg.c

//ggg.h
-sharpifndef ggg_h
-sharpdefine ggg_h

-sharpinclude <stdio.h>

int num;//
void ggg();

-sharpendif /* ggg_h */

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

so there is also a int num variable in ggg.c . When
links the compiled target files of these two files, two int num appear, and the compiler will naturally report an error.

Menu