[prog] C++ strange linking behaviour

Kathryn Hogg kjh at flyballdogs.com
Tue Nov 9 13:00:56 EST 2004


Riccarda Cassini said:
> I always wondered why this is necessary at all - can't the compiler
> just silently ignore "redeclarations" as long as they're identical?
> Why does a tool, that otherwise is perfectly able to build up so
> complex data structures that people even recommend it for RAM testing,
> force the programmer to issue such cumbersome and, IMHO, unnecessary
> boilerplate in each and every header file?
>
> Why not just do something like (expressed in perl pseudocode, for
> brevity):
>
>   if (!exists $decl{$symbol} ) {
>
>     $decl{$symbol} = $declaration;
>     # set up the declaration, the first time it is encountered
>
>   } elsif ($declaration ne $decl{$symbol} ) {
>
>     # issue warning/error
>
>   } else {
>
>     # identical redeclaration encountered - just shut up here...
>
>   }
>
> This logic doesn't seem too complex to me... :-)
> So, is there any reason other than "it's always been that way"?

Part of it is that the guards can speed up compilation.  If the header
gets included twice, the 2nd time or more will be really fast since only a
few lines need to parsed by preprocessor.

Additionally, the guards can prevent recursion:

// A.h
#ifndef KJH_A_H
#define KJH_A_H
#include <B.h>
#endif

// B.h
#ifndef KJH_B_H
#define KJH_B_H
#include <A.h>
#endif

Without the guards, you have a compile that won't stop until you run out
of fd's.

When you check if a declaration is identical above, what are you checking?
 Raw character strings?  Some kind of parsed representation of the code?

What if the code is quite complex like a large class definition or
template definition?

C/C++ compilers do allow duplicate declarations of some symbols. I.e.
extern statements for variables
-- 
Kathryn
http://womensfooty.com



More information about the Programming mailing list