Undef a typedef in C++?
Undef a typedef in C++?
>我正在做一个大项目,它有一个文件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.h
的Elf64_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
为清楚起见,这之所以有效,是因为您基本上重命名了所有名称,但使用单个命令执行此操作,而不必更改所有自己的名称。
- netcat command in c++
- Difference in displaying cv2 Mat
- C++ MFC Libraries in Travis CI
- 如何在OpenSSL中从configuration.h.in获取configuration.h
- 创建具有 new in 函数和"this is nullptr"异常的对象
- IN, OUT, INOUT Parameters
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 有人安装"IITB Simplecpp in mac"吗?
- 从 C 样式字符串中删除子字符串 "in place" 在C++代码中
- 如何修复"error: ‘_1’ was not declared in this scope"?
- Softmax Implementation in C++
- 将 out/in out 参数与 if/switch 的 init 语句一起使用
- IF-nesting in c++
- Gurobi GRBModel and GRBmodel in C++
- Tensorflow Hub in C++
- Centos7 g++ "to_string is not in a member of std"
- InitializeCriticalSectionEx Not Located In KERNEL32.Dll
- 将 lambda 表达式传递给 std::function in C++
- @CPPFLAGS@在 Makefile.in 中意味着什么?
- std::async from std::async in windows xp