“#define”与“#define 1”

"#define" vs "#define 1"

在以下示例中,1 似乎是不必要的(并且可能具有误导性),但我在用于检查 #ifdefs 时多次看到它:

#ifndef __NEWLIB_H__

#define __NEWLIB_H__ 1

使用上述内容与普通的 #define __NEWLIB_H__ 有区别或原因吗?

1 为真,因此您可以在 #if 测试中使用该宏。这对头球后卫来说通常不是很有用,但肯定不会有什么坏处。对于其他可能在布尔表达式中测试的宏,真值肯定有用。

有些人就是喜欢一致性。如果您将 -D TESTME 放在命令行中,这就是 gcc 默认选择的定义。

然而,

#define __NEWLIB_H__ 1

除非在标准库的实现中,否则它并不酷,因为以两个下划线(或一个下划线和一个大写字母)开头的名称保留供实现使用,永远不应在可移植应用程序中使用。

当纯粹用作 #include 守卫时,

没有区别
#ifndef __NEWLIB_H__
#define __NEWLIB_H__

#ifndef __NEWLIB_H__
#define __NEWLIB_H__ 1

不过,总的来说还是有区别的。

编译器错误

#ifndef ABCD
#define ABCD
#endif

int main()
{
#if defined(ABCD) && (ABCD == 1)
   std::cout << "ABCD is 1\n";
#else
   std::cout << "ABCD is not 1\n";
#endif
}

输出字符串"ABCD is 1"

#ifndef ABCD
#define ABCD 1
#endif

int main()
{
#if defined(ABCD) && (ABCD == 1)
   std::cout << "ABCD is 1\n";
#else
   std::cout << "ABCD is not 1\n";
#endif
}

输出字符串"ABCD is not 1"

#ifndef ABCD
#define ABCD 10
#endif

int main()
{
#if defined(ABCD) && (ABCD == 1)
   std::cout << "ABCD is 1\n";
#else
   std::cout << "ABCD is not 1\n";
#endif
}

#define 本身 will replace the symbol with nothing.

另一方面,#define 1,如您所说,将在文件中找到的任何地方用 1 替换该符号。因此,例如,以下代码:

#include <iostream>

#define EXAMPLE "hello"

int main()
{
    std::cout << EXAMPLE;

    return 0;
}

打印

hello

这是因为这里的EXAMPLE"hello"代替了,使得打印语句等价于:

std::cout << "hello";

如果我们将 #define 语句改为:

#define EXAMPLE

This will give a compile error:

main.cpp: In function ‘int main()’:
main.cpp:15:25: error: expected primary-expression before ‘;’ token
     std::cout << EXAMPLE;

至于为什么你会使用第二种形式的 #define,这是因为你可以使用另一个处理器指令 #ifdef:

#include <iostream>

#define EXAMPLE

int main()
{
#ifdef EXAMPLE
    std::cout << "EXAMPLE defined.";
#endif

    return 0;
}

这将打印:

EXAMPLE defined.

因为#ifdef(及其相关的#ifndef)只需要定义符号,我们并不真的需要给它一个值。它只需要在那里工作。

你经常看到这种东西的地方是header guards (which is probably what you're seeing). You can also see it with platform identification, or even to determine whether the compiler is using C++ or not