I am trying to understand the use of the extern expression and global variable in header files, so I came up with the following test program written in C.
File main.c
//main.c
Global.h file
#ifndef _GLOBAL_H #define _GLOBAL_H
and the AddValue.c file that implements the AddToValue function.
#include "global.h" int AddToValue() { nValue++; nExternValue++; }
I compiled the application using gcc and ran it:
$ gcc main.c AddValue.c -o test $./test 0 6 1 7
I ran the application 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 generate an error? I, although the variable nValue will be declared several times, and this will lead to 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.
source share