简体   繁体   English

如何在C中#define变量

[英]How to #define variable in C

I have a file called config.h with the following... 我有一个名为config.h的文件,其中包含以下内容...

#define GL_DOOM

Then I have the following in another file m_misc.c... 然后我在另一个文件m_misc.c中有以下内容...

#include "config.h"
...
#if ((defined GL_DOOM) && (defined _MSC_VER))
LOGD("Using glboom-plus.cfg");
#define BOOM_CFG "glboom-plus.cfg"
#else
LOGD("Using prboom-plus.cfg");
#define BOOM_CFG "prboom-plus.cfg"
#endif

But it says... 但它说...

05-02 14:40:24.789: D/Doom(2966): Using prboom-plus.cfg 05-02 14:40:24.789:D / Doom(2966):使用prboom-plus.cfg

What is the deal here? 这是怎么回事? I am new to C so what am I missing? 我是C语言的新手,所以我想念什么?

Let's take the following code: 让我们看下面的代码:

#define GL_DOOM
#define _MSC_VER

#if ((defined GL_DOOM) && (defined _MSC_VER))
LOGD("Using glboom-plus.cfg");
#else
LOGD("Using prboom-plus.cfg");
#endif

I can compile that code with g++ -E which will output the result of the preprocessor. 我可以用g++ -E编译该代码,该代码将输出预处理器的结果。 Let's look at that output. 让我们看一下输出。

# 1 "blah.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "blah.c"

LOGD("Using glboom-plus.cfg");

So, to me, this implies that you probably don't have both GL_DOOM and _MSC_VER defined. 因此,对我来说,这意味着您可能没有同时定义GL_DOOM_MSC_VER


You might verify this with a test that looks something like: 您可以通过类似于以下内容的测试来验证这一点:

#include "config.h"

#ifndef GL_DOOM
#error GL_DOOM is not defined
#endif

#ifndef _MSC_VER
#error _MSC_VER is not defined
#endif

It's also worth noting something. 这也值得注意。 _MSC_VER is a preprocessor symbol that is defined almost strictly by Microsoft Visual Studio . _MSC_VER是几乎由Microsoft Visual Studio严格定义的预处理器符号。 If you're not compiling with that software, then the expectation would be that it would not be defined. 如果您不使用该软件进行编译,则期望它不会被定义。

#include "config.h"

that includes the #define GL_DOOM . 包括#define GL_DOOM

...
#if ((defined GL_DOOM) && (defined _MSC_VER))

That checks whether both, GL_DOOM and _MSC_VER are defined. 检查是否同时定义了GL_DOOM_MSC_VER

Since GL_DOOM is defined, either your preprocessor is totally broken, or _MSC_VER is not defined. 由于已定义GL_DOOM ,因此您的预处理器已完全损坏,或者_MSC_VER

The check 支票

#if ((defined GL_DOOM) && (defined _MSC_VER)) 

will only evaluate to true if both the conditions are met. 如果两个条件都满足,则将评估为true。 You have not specified whether you have defined _MSC_VER in the header file. 您尚未指定是否在头文件中定义了_MSC_VER。 That is probably the reason why it is executing the else condition. 这可能是它执行else条件的原因。

If you want to log when either of those are defined in the header file, use the OR operation instead: 如果要记录在头文件中定义的任何一个时,请改用OR操作:

#if (defined (GL_DOOM)) || (defined (_MSC_VER))

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

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