简体   繁体   English

具有多个翻译单元的LNK2005错误

[英]LNK2005 error with multiple translation units

I'm writing a small arbitrary-precision arithmetic library, and I have encountered a problem: 我正在编写一个小的任意精度算术库,但遇到了一个问题:

I have exception class, derived from std::exception , in my exception.h and exception.cpp . 我在exception.hexception.cpp中有一个从std::exception派生的异常类。 Exception.h is included by vector.h , and vector.h , in turn, is included by my_long.h. Exception.hvector.hvector.h包括,反过来,由my_long.h包括在内。

So the problem is: when I'm including my_long.h in main.cpp and my_long.cpp, I'm getting a redefinition linker error LNK2005 for all functions in my exception class, which is quite logical, because I'm including this class in two different translation units and then trying to link them together. 所以问题是:当我在main.cpp和my_long.cpp中包括my_long.h时,我在异常类中的所有函数都得到了重新定义链接器错误LNK2005 ,这是很合逻辑的,因为我包括了在两个不同的翻译单元中进行分类,然后尝试将它们链接在一起。

Is there any possible workarounds, or what am I doing wrong? 有没有可能的解决方法,或者我做错了什么?

You have two choices. 您有两种选择。 You can either mark all of the functions in my_long.h as inline, which allows multiple identical definitions, or you can move the function definitions to my_long.cpp and put forward declarations for them in my_long.h. 您可以将my_long.h中的所有函数标记为内联,从而允许多个相同的定义,也可以将函数定义移至my_long.cpp并在my_long.h中提出它们的声明。

Typically, to keep the header file readable, you should do the second except for very small functions. 通常,为了使头文件可读,除了非常小的功能外,您应该执行第二步。

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

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