I have problem with multiply declaration in c++, but not in c.
You could see code for more information.
file main.c
#ifndef VAR
#define VAR
int var;
#endif
int main(){}
file other.c
#ifndef VAR
#define VAR
int var;
#endif
Compile with gcc
gcc main.c other.c
>> success
Compile with g++
g++ main.c other.c
Output:
/tmp/ccbd0ACf.o:(.bss+0x0): multiple definition of `var'
/tmp/cc8dweC0.o:(.bss+0x0): first defined here
collect2: ld returned 1 exit status
My gcc and g++ version:
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.
Your code is formally incorrect in both C and C++ due to multiple definitions of variable
var. It is just that this type of error was traditionally overlooked by C compilers as a popular non-standard extension. This extension is even mentioned in C language specificationBut formally, you have absolutely the same multiple-definition error in both C and C++ languages. Ask your C compiler to behave more pedantically (disable extensions, if it has an option for that) and your C compiler shall also generate the very same error as your C++ compiler.
Again, you code contains multiple definitions of variable
var, which is an error in both C and C++. Your#ifdefdirectives do not solve anything at all. Preperocessor directives cannot help you here. Preprocessor works locally and independently in each translation unit. It can’t see across translation units.If you want to create a global variable (i.e. the same variable shared by all translation units), you need to make one and only one definition of that variable
in one and only one translation unit. All other translation units should receive non-defining declarations of
varThe latter is typically placed in a header file.
If you need an individual, independent variable
varin each translation unit, simply define it in each translation unit as(although in C++ this usage of
staticis now deprecated and superseded by nameless namespaces).