Search code examples
c++scopelinkermacrosc-preprocessor

C++ defined ?macro? visible in header yet missing in implementation (linker reports unresolved external)


I have some class for specific debug purposes, so I use it only when interested in given functionality

to prevent source rubbish when not needed, I tried to handle it by preprocessor, so the structure is something like this:

===main.cpp===
#define nowUseTmp
#include "tmp.h"
/*normal code which accesses tmp via macros*/
===EOF===

===tmp.h===
#ifdef nowUseTmp
/* class declaration */
/* macros to use static methods on class*/
#else
/*empty macro variants, so they may freely stay in code where needed*/
#endif
===EOF===

===tmp.cpp===
/*EXPECTED PLACE OF PROBLEM*/
#ifdef nowUseTmp
/* definitions */
#endif
===EOF===

problem is, that when I enable nowUseTmp (before the_very_first/each include), linker reports unresolved external (like if the macro was defined in header and NOT defined in the cpp file)

Question: Why / How / What is better approach

I expect that cpp files are translated individually, without knowledge of include chain (thus cannot have info about the define)

Is that the case? If so, how to workaround, so I can have constant "tmp.*" files between multiple projects, and manage enabled/disabled individually per project (i.e. not to use define inside relevant header)

Just to clarify

->when I place "#define tmpUseNow" inside relevant header (tmp.h), all works fine

->relevant header (tmp.h) is included from relevant definition file (tmp.cpp)

->same behavior tested with simplified project with only three files as in example

-> relevant files (tmp.h, tmp.cpp) are assumed constant files shared between many projects (so I do not see how to order them to include predetermined third file with definitions, which would be individual for projects that use them)


Solution

  • Yes, each cpp file is processed independently. If I were you, I'd make sure to include tmp.h in tmp.cpp, and I'd only ever define nowUseTmp in tmp.h.