2

Since preprocessor don't report an error when checking value of preprocessor's symbol that isn't actually defined (usually due to the lack of #include "some_header.h"), I use this cumbersome three line construction with "defined":

#if !defined(SOME_SYMBOL)
#error "some symbol isn't defined"
#endif
#if SOME_SYMBOL == 1
// Here is my conditionally compiled code
#endif

And the way with "#ifndef" is the same.
Is there a more elegant way to perform this check?

1 Answers1

0

In your construction you could use an else block to skip the check for defined:

#if SOME_SYMBOL == 1
// Here is my conditionally compiled code
#else
// error
#endif

But in principle the comments are right. #if !defined and the shorthand #ifndef are the two available versions.

Currently, you are checking if SOME_SYMBOL is equals to 1. Do you execute different code based on that value ? If not, you could simply use:

#ifdef SOME_SYMBOL
// Here is my conditionally compiled code
#else
// error
#endif

And now it's a short step to the typical c++ include guards. Copying from that wikipedia link, here is a grandparent.h file:

#ifndef GRANDPARENT_H
#define GRANDPARENT_H

struct foo {
    int member;
};

#endif /* GRANDPARENT_H */

Now, even if you end up including this header twice, it will only be executed once.

lhk
  • 27,458
  • 30
  • 122
  • 201