简体   繁体   English

使用相同名称的typedef替换预处理器宏

[英]Replace preprocessor macro by typedef of the same name

I want to replace a macro with a proper typedef with the same name. 我想用一个具有相同名称的正确typedef替换宏。 I have 我有

#define FooType char*

in a third party library and this breaks some of my code (more precisely: some code I am forced to use and which I can't change by myself). 在第三方库中,这打破了我的一些代码(更准确地说:我被迫使用的一些代码以及我自己无法改变的代码)。 I want to replace it by a typedef of the same name and then #undef the macro. 我想用一个同名的typedef替换它,然后#undef宏。 I tried something like that: 我试过这样的事情:

#define TMP_MACRO FooType
#undef FooType
typedef TMP_MACRO FooType;
#undef TMP_MACRO

But the preprocessor expands this to: 但预处理器将其扩展为:

typedef FooType FooType;

(at least that is what g++ -E told me). (至少那是g++ -E告诉我的)。 So the macro TMP_MACRO is not expanded immediatelly. 所以宏TMP_MACRO不会立即扩展。 As 'FooType' is not there, it does not compile. 由于'FooType'不存在,因此无法编译。

How can I replace the macro FooType by a proper type and undefine the macro afterwards? 如何用适当的类型替换宏FooType并在之后FooType定义宏? Or is this impossible? 或者这不可能吗?

A typedef declaration is usually on one line, but line numbers mean nothing to the compiler. typedef声明通常在一行上,但行号对编译器没有任何意义。

typedef FooType
#undef FooType
FooType;

Why not simply 为什么不简单

#undef FooType
typedef char* FooType

The output you're getting is correct, since you instruct the preprocessor to replace TMP_MACRO with FooType (the fact that you undef FooType afterwards counts for nothing in regards to this). 你得到的输出是正确的,因为你指示预处理器,以取代TMP_MACROFooType (你其实undef FooType事后算个什么的问候这个)。

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

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