Copy-Paste of source files; Compilation Guard Band’s worst enemy.

10 05 2008


In big projects, sometimes you want to write almost similar classes, which is more or less similar. For instance, assume you have a request base class, and the derived classes should implement some common virtual functions.

Usually one easy method is to copy-paste one of the existing derived class so that by making minor change, we can start the next derived class. While doing so, just remember – you are making one of the dangerous, hard to detect bug. When you try to compile your source, the second derived class you created, will show the error – “error C2065: ‘CDerived2’ : undeclared identifier”


The real culprit here is the compilation guard band. You might notice for avoiding multiple include, your header file contains a macro as follows,

#if !defined(AFX_DIALOGDLG_H__75E88A77_A1A2_4417_9815_D8F2DFB44506__INCLUDED_)
#define AFX_DIALOGDLG_H__75E88A77_A1A2_4417_9815_D8F2DFB44506__INCLUDED_
…

#endif // !defined(AFX_DIALOGDLG_H__75E88A77_A1A2_4417_9815_D8F2DFB44506__INCLUDED_)

This means, the compiler will go through the declarations inside the compilation guard bands, only once. If you create a class by using class wizard, the class wizard will automatically generate unique compilation guard band for each classes.

Can you assume what happens when you create new classes by copy pasting? While copy-pasting, we usually forgot to change the compilation guard bands and which result in two different classes with same compilation guard band. So while compiling; only one of the classes will be declared.


Its safe to avoide file copy-paste to create new classes. Even if you do, don’t forget the compilation guard bands. 😉


Targeted Audience – Intermediate.