views:

229

answers:

4

I have a class with two possible implementations, depending on a preprocessor switch. The way I have handled this is to create "src\CompSwitch1\class.h" and "src\CompSwitch2\class.h". In my standard include file, I use

   #ifdef CompSwitch1
        #include "CompSwitch1\class.h"
    #elif CompSwitch2
        #include "CompSwitch2\class.h"
    #else
        #error "Specify CompSwitch1 or CompSwitch2"
    #endif

This works for most of my classes that need two versions. However, on one of them, I get a linker error (lnk2019: unresolved external symbol). I'm using MS Visual Studio 2005 and 2008, and it appears on both of them.

At the top of the .h file, I test against the preprocessor option. Also, although I only referenced the .h file for brevity, there is also a .cpp file for each of these, in the appropriate directory.

A: 

it should really be #ELIF DEFINED( CompSwitch2 ) really. Otherwise you are assuming "CompSwitch2" has been defined with a value of 1 ...

Goz
Not necessarily. Undefined macros are evaluated to 0 when considered in a boolean context.
RaphaelSP
but are defined ones without a value considered to be 1? Personally i always do the DEFINED thing ... cos i've had weird issues in the past by not doing so/
Goz
+1  A: 

It sounds like you might have included the header file for one of the classes, but linked the object file for for the other one, or neither

Nick
A: 

Try to put in the cpp implementation files after they include your header the following preprocessor line(s):

//in compswitch1.cpp
#ifndef CompSwitch1
# error "inconsistent header included"
#endif

//in compswitch2.cpp
#ifndef CompSwitch2
# error "inconsistent header included"
#endif

If you compile wrong header/cpp pairs you should get at least compilation errors and not linking errors. There are much easier to identify/fix ;)

Another possibility is that the cpp-files are not included into compilation at all. Put a message pragma inside the cpp file to see if they get compiled at all:

#pragma message( "Compiling " __FILE__ )

Or try to identify in the build directory if there object files created, which relate to cpp-compilation units.

Hope that helps,
Ovanes

ovanes
A: 

You can use preprocessed cpp file (stage where all includes and macros are expanded).

In VS 2008 right click on your file in Solution Explorer->Properties->C++->Preprocessor and set "Generate Preprocessed File" set "With Line Numbers (/P)". After that right click again your file and choose "Compile". File with extension "i") (e.g. main.i) will be created in the same directory where cpp resides. Open it and see which include file is included.

This method is very handful to solve hard compilation problems (e.g. some macro from system header files replaces something in your code).

dimba