I have a 2 modules (.c files) and one .h header file:
file1.c:
#include <stdio.h>
#include "global.h"
int main()
{
i = 100;
printf("%d
",i);
foo();
return 0;
}
file2.c
#include <stdio.h>
#include "global.h"
void foo()
{
i = 10;
printf("%d
",i);
}
global.h
int i;
extern void foo()
When I do gcc file1.c file2.c everything works fine and I get the expected output. Now, when I initialize variable 'i' in the header file to say 0 and compile again I get a linker error:
/tmp/cc0oj7yA.o:(.bss+0x0): multiple definition of `i'
/tmp/cckd7TTI.o:(.bss+0x0): first defined here
If I just compile file1.c (removing call to foo()) with the initialization in the header file i.e. gcc file1.c, everything works fine. What is going on?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…