如何触发 __cplusplus (C++) #ifdef?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6779663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:40:48  来源:igfitidea点击:

How to trigger the __cplusplus (C++) #ifdef?

c++macros

提问by David Degea

#ifdef __cplusplus
// C++ code
#else
// C code
#endif

The structure is this. My question is, how to actually trigger the #ifdefon?

结构是这样的。我的问题是,如何实际触发#ifdef

I mean, in program? What code I write can turn #ifdefon?

我的意思是,在程序中?我写的什么代码可以开启#ifdef

For example, in this case. is that

例如,在这种情况下。就是它

#define __cplusplus

will turn it on?

会打开吗?

回答by kravemir

"#define __cplusplus"

will let it on?

“#define __cplusplus”

会让它吗?

Yes, it will "let it on".

是的,它会“让它继续”。

__cplusplusshould be automatically defined by C++ compiler. C++ uses different name manglingand the macro often used to make C headers compatible with C++:

__cplusplus应该由 C++ 编译器自动定义。C++ 使用不同的名称修饰和常用于使 C 头文件与 C++ 兼容的宏:

#ifdef __cplusplus
extern "C" {
#endif

...

#ifdef __cplusplus
}
#endif

回答by R. Martinho Fernandes

Just compile it with a C++ compiler and __cplusplusis defined automatically in that case.

只需使用 C++ 编译器编译它,并__cplusplus在这种情况下自动定义。

回答by Puppy

The C++ Standard enforces that __cpluspluswill always be defined in C++ programs. The C Standard obviously does not. This means that the user need go to no effort to enable this machinery.

C++ 标准强制要求__cplusplus始终在 C++ 程序中定义。C标准显然没有。这意味着用户无需费力即可启用此机器。

回答by Jerry Coffin

A C++ compiler defines this automatically.

C++ 编译器会自动定义它。

Since this starts with two consecutive underscores, it is reserved. You are notallowed to define it yourself (i.e., attempting to do so gives undefined behavior).

由于它以两个连续的下划线开头,因此被保留。你是不是允许自己定义(即试图这样做给未定义行为)。