如何重命名一个C预处理宏? [英] How to rename a C preprocessor macro?

查看:66
本文介绍了如何重命名一个C预处理宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个(只读第三方)报头使用:

Consider a (read-only third-party) header lib.h with:

#define XYZ 42

在一个源文件中,我想使用的字对于一个不相关的目的,并且不希望的取代与.但是,相同的源文件中,用于其他用途,我也确实希望访问从没有硬编码.我如何的改名的从,比方说,<6>?

In a source file, I want to use the word XYZ for an unrelated purpose, and do not want the substitution with 42. But, in the same source file, for other purposes, I also do want to access the value 42 from lib.h without hardcoding it. How do I rename the macro from XYZ to, say, LIB_XYZ?

在以下不工作,因为预处理器要在当时的<6>替换发生,但已经未定义:

The following does not work, because preprocessor wants XYZ at the time the LIB_XYZ substitution is made, but XYZ had been undefined:

#include "lib.h"
#define LIB_XYZ XYZ
#undef XYZ

有没有办法诱使预处理器在XYZ丢失之前将LIB_XYZ扩展到最终值?

Is there a way to trick the preprocessor into expanding LIB_XYZ to its final value before XYZ is lost?

推荐答案

不与所述预处理器,至少,不,我知道的.

Not with the pre-processor, at least, not that I am aware of.

然而,对于具有已知类型等在例如简单的常数,有一种替代方法.

However, for simple constants with known type like in your example, there is a workaround.

#include <stdio.h>

// <xyz.h>

#define XYZ 42

// </xyz.h>

enum xyz_constants
{
  LIB_XYZ = XYZ,
};

#undef XYZ

#define XYZ 27

int
main()
{
  printf("old value: %d, new value: %d\n", LIB_XYZ, XYZ);
  return 0;
}

未示出从,该代码被预处理以下面的绒毛.

Not showing the fluff from stdio.h, this code is pre-processed to the following.

enum xyz_constants
{
  LIB_XYZ = 42,
};

int
main()
{
  printf("old value: %d, new value: %d\n", LIB_XYZ, 27);
  return 0;
}

可以此扩展到一定程度上的其它数据类型和特定功能的类似的宏但当然有限制.

You can extend this to some degree to other data types and certain function-like macros but there are of course limits.

无论如何,为什么需要特定的标识符XYZ?你不能为你的宏中使用不同的名字呢?

Anyway, why do you need the particular identifier XYZ? Can't you use a different name for your macro?

这篇关于如何重命名一个C预处理宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆