X-宏重新定义
当我在多个头文件使用的头文件中包含“xmacro.h”时,我收到链接错误:
错误 LNK2005:“char const * * iD_Strings”(?iD_Strings@@3PAPBDA) 已在 header_file.obj 中定义
1.//"xmacro.h"
2.
3.// (1) Define code generating macro
4.
5. #ifndef XMACRO_H
6. #define XMACRO_H
7.
8. #define GENERATE_IDS \
9. X(_Name, "/Name") \
10. X(_ID, "/ID")
11.
12. // (2) Define X-Macro for generating enum members
13.
14. #define X(id, idString) id,
15. enum IDs
16. {
17. ID_LOWERBOUND = -1,
18. GENERATE_IDS
19. NUM_IDS
20. };
21. #undef X
22.
23. // (3) Define X-Macro for generating string names
24.
25. #define X(id, idString) idString,
26. const char* iD_Strings[] =
27. {
28. GENERATE_IDS
29. NULL
30. };
31. #undef X
32.
33. #endif
当我在第 23 行定义用于生成字符串名称的 X-Macro 时,它会生成错误。我如何使用单个宏而不重新定义它?
When i include the "xmacro.h" in header file which is used by multiple header files i get linking error:
Error LNK2005: "char const * * iD_Strings" (?iD_Strings@@3PAPBDA)
already defined in header_file.obj
1.//"xmacro.h"
2.
3.// (1) Define code generating macro
4.
5. #ifndef XMACRO_H
6. #define XMACRO_H
7.
8. #define GENERATE_IDS \
9. X(_Name, "/Name") \
10. X(_ID, "/ID")
11.
12. // (2) Define X-Macro for generating enum members
13.
14. #define X(id, idString) id,
15. enum IDs
16. {
17. ID_LOWERBOUND = -1,
18. GENERATE_IDS
19. NUM_IDS
20. };
21. #undef X
22.
23. // (3) Define X-Macro for generating string names
24.
25. #define X(id, idString) idString,
26. const char* iD_Strings[] =
27. {
28. GENERATE_IDS
29. NULL
30. };
31. #undef X
32.
33. #endif
it generates an error when i define X-Macro for generating string names at line 23. how would i use a single macro without redefining it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的头文件包含
iD_Strings
的定义。当您从不同的源文件中包含它时,它会被多次链接。即使定义相同,也会导致冲突。您可以将
iD_Strings
声明为static
(C 方式)或将其包装在匿名命名空间(C++ 方式)中来解决此问题。Your header file contains the definition of
iD_Strings
. When you include it from different source files, it gets linked in multiple times. That results in a conflict even if the definitions are identical.You could declare
iD_Strings
asstatic
(the C way) or wrap it in an anonymous namespace (the C++ way) to get around this problem.执行 X-Macros(我一直将其称为列表宏)的更好方法是将运算符作为参数传递给列表,然后您可以同时保留多个“运算符”:
请注意,您仍然需要声明标识符是唯一的,但是调用 GENERATE_IDS() 宏来声明对象确实属于 .c/.c++ 主体,而不是标头。
A better way to do X-Macros (which I've always called list macros) is to pass the operator as a parameter to the list, then you can keep multiple "operators" around at the same time:
Note you still have to declare the identifiers uniquely, but the invocation of the GENERATE_IDS() macro to declare objects really belongs in a .c/.c++ body and not a header anyway.