LNK 2005链接Visual Studio 2010中函数的错误,但不链接类的错误
LNK 2005 link errors for functions but not for class in Visual Studio 2010
我现在正在构建一个C++DLL库。今天我遇到了一个令人困惑的问题:在这个库中,我可以定义类,但不能定义函数。更具体地说,我给出了以下代码来说明我的问题:
namespace fundamental
{
class Tree
{
public:
Tree() {};
~Tree() {};
int x;
};
/*int anyfunction()
{
return 1;
}*/
}
上面的定义在头文件中,该文件将被其他文件调用。我的问题是,如果我评论了函数部分(int anyfunction()),一切都很好,但如果我添加了这个函数,我会得到以下错误:
page_analysis.obj : error LNK2005: "int __cdecl fundamental::anyfunction(void)" (?anyfunction@fundamental@@YAHXZ) already defined in geo_box.obj
1>pa_region_properties.obj : error LNK2005: "int __cdecl fundamental::anyfunction(void)" (?anyfunction@fundamental@@YAHXZ) already defined in geo_box.obj
我的问题是为什么我只会得到LNK2005错误的函数,而不是类。有什么想法吗?
如果在头文件中定义了某个内容,那么该定义将在包括该头的任何翻译单元(粗略地说,每个源文件)中重复。有时,多个定义是错误的。
类可以在多个翻译单元中定义,只要定义相同;事实上,它们必须在任何使用它们的翻译单元中定义。
函数通常不能,但您可以通过声明它inline
:来允许它
inline int anyfunction() {return 1;}
或者您可以将定义移动到一个单一的源文件,并只在标题中声明它:
// header
namespace fundamental {
int anyfunction();
}
// source file
int fundamental::anyfunction() {return 1;}
很可能您已经通过一个标头将该函数包含在不同的转换单元(也称为cpp文件)中。如果您确实需要内联该函数,请使用"内联":
inline int anyfunction()
{
return 1;
}
HTH Torsten
相关文章:
- 静态数据成员的问题-修复链接错误会导致编译器错误
- Visual Studio mkl_link_tool.exe链接错误
- C++ 实现模板单例类时出现链接错误
- 使用类模板的方法链接错误
- MySQL C++连接器链接错误
- VS 2015 链接错误 无法构建依赖于 libcurl 的项目
- 运行 C++ 单元测试时LNK2005链接错误
- 对 CMake 中'cudaRegisterLinkedBinary'链接错误的未定义引用?
- 链接错误,包括我创建的相同头文件 - C++
- 在Embarcadero C++ Builder中生成的DLL未解决的外部链接错误
- 使用标头保护的多个定义链接错误
- 链接错误:未定义对 stdscr 和 wgetch 的引用
- 使用 Vivek 的 Vcam / 捕获源过滤器构建/链接错误
- 升压program_options中的链接错误
- 使用 g++ 预处理器进行替换会导致链接错误
- 在调试配置中编译工作正常,但发布会给出链接错误
- 相邻矩阵设置链接错误
- 包含常量变量并包含在多个文件中的标头的链接错误
- C++链接错误,我理解但无法解决
- 是什么导致macOS Mojave上的GoogleTest链接错误