简体   繁体   English

预处理器指令不可能定义或取消定义预处理器

[英]Preprocessor directive Impossible define or cancel defining the preprocessor

I'm trying to learn preprocessor directive, so I made a simple example like this: 我正在尝试学习预处理器指令,因此我做了一个简单的示例,如下所示:

using System;

namespace learning
{
    class Program
    {
        static void Main(string[] args)
        {
#define DEBUG
            test();
        }

        private void test()
        {
#if DEBUG
            Console.WriteLine("Debug mode");
#elif RELEASE
            Console.WriteLine("Release mode");
#else
            Console.WriteLine("Debug and release don't defined");
#endif
        }

    }
}

but I got unfortunately this error: 但不幸的是我得到了这个错误:

Impossible to define or cancel defining the preprocessor symbols after the first token in the file 无法定义或取消定义文件中第一个标记之后的预处理器符号

I take this example from a programming book, what is wrong? 我从一本编程书中举这个例子,怎么了?

update (my solution): 更新(我的解决方案):

#define RELEASE
using System;

namespace learning
{
    class Program
    {
        static void Main(string[] args)
        {
#if DEBUG
            Console.WriteLine("Debug mode");
#elif RELEASE
            Console.WriteLine("Release mode");
#else
            Console.WriteLine("Debug and release don't defined");
#endif
            Console.ReadLine();
        }

    }
}

printed result: Debug mode , but should be Release mode . 打印结果: Debug mode ,但应为Release mode What I did wrong? 我做错了什么?

As Neo mentioned, you can define it at the top of your file. 如Neo所述,您可以在文件顶部定义它。

Or, if you want for it to be global, and you are using Visual Studio, you could define it in your project properties (right-click on the project, choose Properties, then go to the Build tab). 或者,如果您希望它具有全局性,并且您正在使用Visual Studio,则可以在项目属性中对其进行定义(右键单击该项目,选择“属性”,然后转到“构建”选项卡)。

That screen would allow you to define the symbol based upon the build configuration (so you could set your symbol for debug builds and have it automatically be removed when you switch configurations). 该屏幕将允许您根据构建配置定义符号(因此您可以为调试构建设置符号,并在切换配置时自动将其删除)。

If you are not using Visual Studio, you could pass your conditional symbols to MSBuild or csc (the command line build or command line c# compiler). 如果不使用Visual Studio,则可以将条件符号传递给MSBuild或csc(命令行生成或命令行c#编译器)。 All of these options would give you the ability to set/unset symbols without changing the source code. 所有这些选项将使您能够设置/取消设置符号而无需更改源代码。

您需要在using语句之前将#define行放在文件的开头

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM