Undef a typedef in C++?

Undef a typedef in C++?

本文关键字:C++ in typedef Undef      更新时间:2023-10-16

>我正在做一个大项目,它有一个文件A.h,其代码有一行

typedef unsigned __int16   Elf64_Half;

另外,由于我在 Linux 上构建并使用dlinfo函数,因此我必须在我的项目中包含link.h文件。这就是它产生冲突的地方,因为我有两个同名的 typedef Elf64_Half .(Linux link.h包括elftypes.h,它也有:typedef unsigned short Elf64_Half;)。

在这种情况下我该怎么办?我唯一的选择是a.h更改我的 typedef 吗?请记住,这并不太容易,因为项目很大,我将不得不在几个地方进行更改。

有没有办法取消定义类型定义或其他东西?

为了澄清,Rahul Manne给出了一个简单的解决方案。 做

#define Elf64_Half The_Elf64_Half_I_dont_care
#include<link.h>
#undef Elf64_Half
#include<A.h>
/*
 * Code here and use Elf64_Half from A.h as you like.
 * However, you can't use Elf64_Half from link.h here
 * or you have to call it The_Elf64_Half_I_dont_care.
 *
 */

这将用The_Elf64_Half_I_dont_care替换link.h中的每个Elf64_Half,因此您不会与A.h发生冲突。 只要您不想显式使用link.h Elf64_Half就可以正常工作。 您只需要记住,来自link.hElf64_Half现在称为The_Elf64_Half_I_dont_care以防您必须在此文件中显式使用它。

在这种情况下我该怎么办?

一种常见的补救措施是将需要最少可见性的那个放在"编译防火墙"后面。也就是说,创建您自己的抽象/接口来提供您需要的功能,然后通过将包含的文件仅包含在该*.cpp中来将包含文件的可见性限制为*.cpp。当然,该*.cpp文件也不允许包含具有typedef其他定义的标头。

这样,声明就不会引起冲突,因为它们永远不会对同一翻译单元可见。

在您的示例中,您可能会在所需的dlinfo()功能上创建一个包装器。举例说明:

DLInfo.hpp

namespace MON {
class DLInfo {
 public:
 /* ...declare the necessary public/client functionality here... */
 int foo();
 ...
};
}

DLInfo.cpp

#include "DLInfo.hpp"
// include the headers for dlinfo() here.
// these includes should not be in your project's headers
#include <link.h>
#include <dlfcn.h>
// and define your MON::DLInfo implementation here, with full
// ability to use dlinfo():
int MON::DLInfo::foo() {
 ...
}
...
这是我

想出的一个解决方法:如果你先把它定义为其他东西,那么你可以稍后键入它。请参阅示例中的此处(我在使用 g++ 的 OS X 上):

#import <iostream>
using namespace std;
typedef unsigned int uint32;
int main() {
  cout << sizeof(uint32) << endl;
}

该程序的输出为

4

现在考虑这个修改后的程序:

#import <iostream>
using namespace std;
typedef unsigned int uint32;
#define uint32 blah
typedef unsigned long uint32;
int main() {
  cout << sizeof(uint32) << endl;
}

该程序的输出为

8

因此,为了回答您的问题,您需要在代码中添加一行:

#define Elf64_Half Elf64_Half_custom

为清楚起见,这之所以有效,是因为您基本上重命名了所有名称,但使用单个命令执行此操作,而不必更改所有自己的名称。