XNA Cross Platform Compilation Symbols

Garden Flowers 02

I’m writing a single XNA game that should work on a whole bunch of platforms. Actually I’m going for Windows PC, Windows Phone, Xbox 360 and Zune. Which is a full house I reckon.

Anyhoo, this is a bit of a pain, as I have to make the code do different things for the different target devices. For example the Xbox and the Windows PC don’t have a touch screen so I have to simulate this in some way, or provide a different input mechanism for those platforms.

I can do this by using the symbols provided by XNA to let me select code which is passed to the compiler when the program is built. There are a bunch of them.

#if WINDOWS
// only compile this bit if we are targeting Windows PC
#endif

#if XBOX
// only compile this bit if we are targeting XBOX
#endif

#if ZUNE
// only compile this bit if we are targeting ZUNE
#endif

#if WINDOWS_PHONE
// only compile this bit if we are targeting Windows
//  Phone
#endif

It is important that you understand what is happening here. We are not selecting which code to run when the program is active, we are actually selecting which code gets compiled when the program is built.  I could do this to really confuse a programmer:

#if ZUNE
     Har Har
#endif

This is a very nasty thing to do. It means that the program will not compile if the programmer tries to build version for the Zune, it will produce an error when the compiler sees “Har Har” and ties to compile it. It will however work for every other XNA platform.

One other thing worth knowing is that the symbols that you see when editing with Visual Studio depend on the context in which the file was opened. If you have a multi-project solution (one project for Zune, another for Windows and so on) then the project that you open the file from determines which symbols are active when the file is edited and compiled. This is true even if all the entries in the project source are links to the same actual source file. In other words, the view you have of the code depends on where you opened the file from.