By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,401 Members | 793 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,401 IT Pros & Developers. It's quick & easy.

"#if defined" clause intersected

P: n/a
Hi, i'd like to have code blocks A and B if AB is defined
and B and C block if BC is defined.
is the writing below correct ?

Expand|Select|Wrap|Line Numbers
  1. void func(...)
  2. #if defined AB
  3. A
  4. #if defined BC
  5. B
  6. #endif
  7. C
  8. #endif

Nov 7 '10 #1
Share this Question
Share on Google+
3 Replies

Expert Mod 5K+
P: 9,197
The usual practice is to use the macro to provide different code so when you run the program you can see what happened.

Either that, or you need to intercept the translation unit file that is being sent to the compiler.
Nov 7 '10 #2

Expert Mod 5K+
P: 8,916
Since B is always included it should not be inside any preprocessor conditional. Use the symbols to control the inclusion of A and C

Expand|Select|Wrap|Line Numbers
  1. void func(...)
  2. {
  3. #if defined AB
  4. A
  5. #endif
  6. B
  7. #if defined BC
  8. C
  9. #endif
Nov 7 '10 #3

Expert 100+
P: 2,398
Hi, i'd like to have code blocks A and B if AB is defined and B and C block if BC is defined.
Please clarify your requirements. There are four possibilities: neither are defined, both are defined, only AB defined, only BC defined. My guess is that you desire the following behavior:
Block: both, neither, only AB, only BC
A: yes, no, yes, no
B: yes, no, yes, yes
C: yes, no, no, yes
Is this what you want?

You stated the problem in terms of desired behavior for each control variable. It would be clearer to state the inclusion rules for each block:
Block A is present if AB is defined.
Block B is present if either AB or BC are defined.
Block C is present if BC is defined.
(If that is indeed the behavior you want.)

Expand|Select|Wrap|Line Numbers
  1. #if defined(AB)
  2. A
  3. #endif
  4. #if defined(AB) || defined(BC)
  5. B
  6. #endif
  7. #if defined(BC)
  8. C
  9. #endif
I elected to use #if syntax instead of #ifdef syntax in order to support the logical expression for block B. I then used the same syntax for blocks A and C for consistency. In my opinion the inclusion logic is harder to understand if you nest the preprocessor statements.

Suppose you only want to include block C if BC is defined, but AB isn't. Then you would do this:
Expand|Select|Wrap|Line Numbers
  1. #if !defined(AB) && defined(BC)
  2. C
  3. #endif
Nov 8 '10 #4

Post your reply

Sign in to post your reply or Sign up for a free account.