views:

150

answers:

7

Hey,

Is there a way to deliberatly trigger a compilation error when a certain condition is satisfied on Visual Studio 2008?

+2  A: 

In C++ you can use macros like the following to cause a compile time assert when a specified constant condition is false

#define COMPILE_ASSERT(expr) extern int __assertutil[(expr) != 0]

COMPILE_ASSERT(42 != 8);  // Fine
COMPILE_ASSERT(42 == 8);  // Error

This works because in the case that the expression is false it will have a constant value of 0. Arrays in C++ can not have a constant size of 0 and it leads to a compilation error.

JaredPar
This is the closest to what I was looking for, but in C#
Ciwee
+8  A: 

You can use the #error pre-processor feature.

You use it like such:

#ifdef WIN32
    ... code for windows
#else
    #error only windows is supported
#endif
chollida
A: 

There are language specific pre-processor directives. In C#:

#define DEBUG class MainClass  {
    static void Main() 
    {
#if DEBUG
#error DEBUG is defined
#endif
    } 
}

From MSDN.

RossFabricant
+2  A: 

how about the compiler directive #error?

kenny
A: 

int i = (float)(5.0);

Chris Ballance
A: 

Thank you everyone for the answers, but I was looking for something more like a method that I could call to "decide" whether there's an error or not.

Thank you again.

Ciwee
This still doesn't make sense. You can't "call" anything during compilation.
AndreyT
That's why this question has no answer
Ciwee
A: 

I wonder if you're looking for a way to validate the source code before compilation. If so, you could use a pre-build step and fail it (exit with a code other than 0) to abort compilation.

romkyns