views:

738

answers:

5

Im looking to use:

#define

and

#if

to allow me to simulate potentially absent hardware during unit tests. What are the rules for useing the #define statements?

i.e. what is its default scope? can I change the scope of the directive?

+2  A: 

Hi,

From MSDN, its scope is the file

Chris Kimpton
A: 

Although could you not go down the route of Mock objects, ala Mock.Rhinos ?

Chris Kimpton
+3  A: 

As Chris said, the scope of #define is just the file. (It's worth noting that this isn't the same as "the class" - if you have a partial type, it may consist of two files, one of which has symbol defined and one of which doesn't!

You can also define a symbol project-wide, but that's done with project properties or a compiler switch rather than being specified in source code.

Jon Skeet
+1  A: 

Yes as Chris mentioned, its scope is the whole file. You can use the defined keyword anywhere in the file.

i.e;

#define something
... some code ...

and in any method, class body or namespace, you could use it like;

#if something
  ... some conditional code ...
#else
  ... otherwise ...
#endif
yapiskan
A: 

The scope of a preprocessor directive starts when it's parsed from the source and persists until directed otherwise. If you do want to limit the scope of a preprocessor directive, use the "undef" declaration it switch off when your done with it.

#include <iostream>
using namespace std ;
int main()
{
  #define someString "this is a string"
  cout<<someString<<endl;
  #undef someString  // scope of someString ends here
  cout<<someString<<endl; //this causes a compile error
  return 0 ;
}
Gearoid Murphy