How to use #if to decide which platform is being compiled for in C#

混江龙づ霸主 提交于 2019-12-03 07:42:39

You can add any constants you want to the .csproj file. These can be put into conditional property groups like the one below.

 <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
    <DefineConstants>TRACE;X64</DefineConstants>
    ...
 </PropertyGroup>

For my Release x64 build, I have defined a X64 constant that I can use like this:

#if X64

#endif
maxwellb

Make sure your design considers whether this needs to be known at compile time or at runtime. If it is compile time, then yes, you will probably need to define a constant. This can be passed on the command line, or if using Visual Studio or MSBUILD, through a configuration. Change the configuration and build again.

If it is runtime, search through the answers to questions such as How to know a process is 32-bit or 64-bit programmatically... and friends.

However, it is also possible that this distinction may not matter, depending on the needs of your application. .NET manages its own memory, and nothing is stopping your built-for-x86 assembly from running on a 64-bit machine. If you are interopping with unmanaged code, are there any externals from your library that can tell you what sizes you should be using, instead of assuming?

You can also just define a symbol (e.g. _x64) in the project properties for the x64 platform. Open the properties dialogue of your project, select the x64 platform, on the Build page, just put "_x64" into the "Conditional compilation symbols" box.
Make sure to do this for both debug and release configuration.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!