LNK 2005链接Visual Studio 2010中函数的错误,但不链接类的错误

LNK 2005 link errors for functions but not for class in Visual Studio 2010

本文关键字:链接 错误 Visual 2005 Studio 2010 LNK 函数      更新时间:2023-10-16

我现在正在构建一个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