【问题标题】:#ifdef not working as expected with precompiled headers#ifdef 在预编译头文件中无法正常工作
【发布时间】:2013-07-31 10:47:25
【问题描述】:

我有如下部分代码:

#define FEATURE_A 1

void function()
{
// some code

#ifdef FEATURE_A
    // code to be executed when this feature is defined
#endif

// some code

}

程序不执行 #ifdef - #endif 内的代码。但是当我将 #ifdef 更改为 #ifndef 并删除 #define 宏时,代码会被执行。下面的代码按预期工作。

//#define FEATURE_A 1

void function()
{
// some code

#ifndef FEATURE_A
    // code to be executed when this feature is defined
#endif

// some code

}

谁能解释为什么在第一种情况下 #ifdef - #endif 内的代码没有执行,而在第二种情况下它可以工作?谁能告诉我什么设置可能有问题?

不确定这是否重要,我使用的是 Visual Studio 2010。

提前致谢

更新: 当我清理并重新运行时,第二个也不起作用。它仅在编辑器中显示为启用的代码。

当我在 project->property->Configuration Properties-> c/c++ -> Preprocessor 中定义宏时,它们都工作正常。

【问题讨论】:

  • 你确定你在某处没有#undef FEATURE_A吗?
  • 如果您想在预处理后查看代码,请使用-E 标志进行编译
  • 你需要发布一个表现出这种行为的整个程序,否则它没有任何意义。
  • 是的,我确定。我刚刚检查过了。
  • 我记得我在使用 Visual Studio 时遇到了很多问题,有时有助于清除它为项目保留的目标文件。试试看 - 也许会有所帮助

标签: c++ macros


【解决方案1】:

这可能是因为 Microsoft 如何实现预编译的标头。你其实有

#define FEATURE_A 1
#include "stdafx.h" // <- all code even ascii art before that line is ignored.

void function()
{
// some code

#ifdef FEATURE_A
    // code to be executed when this feature is defined
#endif

// some code

}

在预编译头文件和所有工作之后移动它:

#include "stdafx.h" // <- all code even ascii art before that line is ignored.
#define FEATURE_A 1

void function()
{
// some code

#ifdef FEATURE_A
    // code to be executed when this feature is defined
#endif

// some code

}

【讨论】:

    【解决方案2】:

    就我而言,我有多个Platform,所以我需要为每个Platform 定义Preprocessor

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      • 2016-01-15
      • 1970-01-01
      相关资源
      最近更新 更多