Search code examples
c++c-preprocessor

Using #ifdef or #if defined() to find where a variable is (not) defined


I have a situation in which #ifdef is telling me that something is not defined, and yet it proceeds to compile a line as if it is defined. I can't figure out how that can be.

The wider context is that I am banging my head against a brick wall trying to resolve this question. I am trying to determine the point at which SERVICE_STATUS is defined in both a project that compiles, and one that doesn't. As far as Visual Studio 2015 is concerned, if I right click on the word SERVICE_STATUS and go to its definition, in both cases I am taken to the same file: winsvc.h. So I don't think that paths are an issue.

All of which has led me to introducing the following five-line check in various places to see if I can understand where SERVICE_STATUS is included/defined:

#if defined(SERVICE_STATUS)    // or #ifdef SERVICE_STATUS
#pragma message( "SS is defined" )
#else
#pragma message( "SS is NOT defined" )
#endif

In all cases, including just prior to the point where SERVICE_STATUS is used in both the compiling and the non-compiling cases, the only message ever printed is SS is NOT defined. This is the line that does or does not compile, and I can prove it is being parsed by causing deliberate errors immediately before it:

static SERVICE_STATUS _serviceStatus;

Has my head been banged too many times to notice the obvious schoolboy error in my usage of #ifdef or #if defined() (I've tried both)? Alternatively, how this could possibly compile if SERVICE_STATUS is undefined?

Here's a sketch of the context in which this occurs (in the file serverapplication.h from the Poco distribution at pocoproject.org):

...    // lots of irrelevant lines omitted...
[5LC]  // apply my 5-line check
#include <ThisFile>
#include <ThatFile>
[5LC]  // check again and find no change due to header inclusion
...    // many more lines skipped...
[5LC]  // one last check prior to using SERVICE_STATUS - still no change
static SERVICE_STATUS _serviceStatus;  // variable results!?!?

If you want the full context, see the problem I'm trying to fix for links to a zipped project in which I have been able to reproduce this problem independent of my own project... but please respond to that issue separately.


Solution

  • SERVICE_STATUS is a type definition that was defined with typedef; the answer in your other question contains a link to the documentation of it.

    #ifdef is only used to determine if a name was defined as a macro with #define (or via compiler options), you can't use it to test whether a type, variable, or function has been defined. It's part of the preprocessor, not the compiler, so it doesn't know anything about those elements of the code.