Wednesday, 6 May 2009

Preprocessor directives and conditional compilation

If you want different code to be compiled at build time under different conditions you can use preprocessor directives. Using the hash (#) symbol you can write code that the compiler responds to.

A common example of this is the need to use different code in 64 bit and 32 bit applications*.

#If PLATFORM = "x64" Then
'put your 64 bit specific code here
#else
'you know
#End If

In this example we're poking the project's platform setting at compile time and acting accordingly. If the platform is set to 64 bit, the first set of code will be compiled. If the platform is set to 32 bit then the second set of code will be compiled.

You can define your own conditional compiler constants by using the #Const directive (only private to the file in which it is declared), or in the Project Properties dialog (which then has a public scope to all files in the project).


*Of course in some applications it might be more suitable to identify the bitness of the OS at runtime like this:

Private Shared Function Is64Bit() As [Boolean]
    Return Marshal.Sizeof(GetType(IntPtr)) = 8
End Function

No comments:

Post a Comment

Comments are moderated, so you'll have to wait a little bit before they appear!