有条件的预处理难题

时间:2014-04-09 01:22:02

标签: c++ visual-c++ visual-studio-2012

我遇到一个问题,我似乎无法让条件#define预处理器正常工作。例如:

#define WIN32_BUILD
#ifdef WIN32_BUILD
  #define PCH "stdafx.h"
#else
  #define PCH "xyz.h"
#endif

#include PCH

如果我使用这个表单,编译器会告诉我它找不到'stdafx.h'。好的,这看起来很奇怪,所以如果我将代码更改为....

#define WIN32_BUILD
#ifdef WIN32_BUILD
  #define PCH "xyz.h"
#else
  #define PCH "stdafx.h"
#endif

#include PCH

然后PCH中定义的文件被拾取,一切都编译好了。这对我来说似乎很奇怪,几乎就像预处理器忽略#if指令并只使用它遇到的所有#defines一样。

显然我做错了,我希望有人可以帮我理解这一点。

2 个答案:

答案 0 :(得分:3)

当项目启用预编译标题功能时,预处理器会忽略#include" stdafx.h"

之前的所有内容。

所以你的#define语句会被忽略。

答案 1 :(得分:0)

TL:DR; #define定义符号,#ifdef测试符号是否定义,而不是它是否有值。

#define WIN32_BUILD

这定义了一个预处理器令牌WIN32_BUILD。令牌没有价值。您使用令牌的任何地方' WIN32_BUILD'预处理器将替换空字符串,即没有。

#ifdef WIN32_BUILD

检查是否定义了预处理器令牌WIN32_BUILD。是的,你刚刚定义了它。

#ifdef WIN32_BUILD
// true - this code is included.
#define PCH "stdafx.h"

这定义了预处理器令牌PCH,并为其赋值" stdafx.h"

#else
#define PCH "xyz.h"
#endif

此代码被忽略,因为WIN32_BUILD 定义。

看起来好像你在期待' ifdef'如果表达式未定义/ to / something,则仅评估为true。

#define a
#define b SOMETHING

#ifdef a
// you are expecting this to be ignored
#endif

#ifdef b
// and expecting this not to be ignored
#endif

#ifdef#if defined(...)做同样的事情。

#define a
#define b SOMETHING

#if defined(a) && defined(b)
// this code will be evaluated, both tokens are defined.
#endif

预处理器令牌的这一功能通常用于支持条件功能:

#if HAVE_CPP11_OVERRIDE_KEYWORD
#define OVERRIDE_FN override
#else
#define OVERRIDE_FN
#endif

struct A {
    virtual void foo() {}
};

struct B : public A {
    void foo() OVERRIDE_FN {}
};

在上面的代码中,override关键字仅在系统支持时添加(在代码之外确定)。

因此override的编译器会看到

struct B : public A {
    void foo() override {}
};

没有它的编译器

struct B : public A {
    void foo() {}
};

注意:" ifdef"是" ifndef":

#define a
#define b SOMETHING
#undef c
//#define d // << we didn't define it.

int main() {

#ifdef a
#pramga message("a is defined")
#else
#pramga message("a is UNdefined")
#endif

#ifdef b
#pragma message("b is defined")
#else
#pramga message("b is UNdefined")
#endif

#ifdef c
#pramga message("c is defined")
#endif
#else
#pramga message("c is UNdefined")
#endif

#ifdef d
#pramga message("d is defined")
#endif
#else
#pramga message("d is UNdefined")
#endif

#ifndef d
#pragma message("d is not defined")
#endif

#ifndef a
#pragma message("a is not defined")
#endif

    return 0;
}

您可以指定预处理器令牌数值,并使用#if

对其进行测试
#if _MSC_VER
#define WIN32_BUILD 1
#else
#define WIN32_BUILD 0
#endif

#if WIN32_BUILD
#include <Windows.h>
#endif

但是,特别是在进行跨平台编程时,人们倾向于使用ifdef变体而不是数字检查,因为值检查要求您明确确保所有标记都使用值定义。只需在需要时定义它们就容易多了。

相关问题