实现提升函数指针时出错LNK2005

error LNK2005 while implementing boost function pointer

本文关键字:出错 LNK2005 指针 函数 实现      更新时间:2023-10-16

我正在尝试这段代码

演示.hpp

#include <boost/function.hpp>
#include <boost/bind.hpp>
using namespace std;
typedef boost::function<int(int,int)>func;
class funcPointer
{
public:
    void add_call(func);
};

演示.cpp

#include <iostream>
#include "demo.hpp"
void funcPointer::add_call(func f)
{
    cout << "Result of add: " << f(5,7) <<endl;
}

主.cpp

#include "demo.cpp"
int add(int x,int y)
{
    cout << "x: " << x <<endl;
    cout << "y: " << y <<endl;
    return x + y;
}
int main()
{
    funcPointer *fun = new funcPointer;
    fun->add_call(boost::bind(add, _1, _2));    
    return 0;
}

编译时出现以下错误:

demo.obj : error LNK2005: "public: void __thiscall funcPointer::add_call(class boost::function<int __cdecl(int,int)>)" (?add_call@funcPointer@@QAEXV?$function@$$A6AHHH@Z@boost@@@Z) already defined in main.obj
E:vs_c++boost_func_ptrDebugboost_func_ptr.exe : fatal error LNK1169: one or more multiply defined symbols found

我不明白这是什么错误,有人可以帮我解决这个错误吗?

不要#include源文件!

在您的情况下(我只是在这里猜测),文件demo.cpp是项目的一部分,因此它被编译并链接以创建可执行文件。问题是,由于您还将该源文件作为头文件包含在内,因此该函数也在main.cpp中定义。

main.cpp中,您应该包含文件demo.hpp