I'm trying to understand the usage of extern and global variable declaration in header files so I came up with the following test program written in C.
The main.c file
//main.c
#include "global.h"
#include <stdio.h>
int nExternValue = 6;
int main(int argc, char* argv[])
{
printf("%d \n", nValue);
printf("%d \n", nExternValue);
AddToValue();
printf("%d \n", nValue);
printf("%d \n", nExternValue);
}
The global.h file
#ifndef _GLOBAL_H
#define _GLOBAL_H
//WRONG! do not declare a variable here
int nValue;
//OK! extern variable makes it a global accessable variable
extern int nExternValue;
//OK! function prototype can be placed in h file
int AddToValue();
#endif
and a AddValue.c file which implements the AddToValue function.
#include "global.h"
int AddToValue() {
nValue++;
nExternValue++;
}
I compiled the app using gcc, AND ran it:
$ gcc main.c AddValue.c -o test
$./test
0
6
1
7
I complied the app using g++ and got the following linker error:
$ g++ main.c AddValue.c -o test
/tmp/ccFyGDYM.o:(.bss+0x0): multiple definition of `nValue'
/tmp/cc3ixXdu.o:(.bss+0x0): first defined here
collect2: ld returned 1 exit status
Why doesn't the gcc linker produce an error? I though the nValue variable would be declared multiple times and that would produce an error!
$ gcc --version
gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ g++ --version
g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.