-1

您好我正在尝试使用 dll 运行应用程序。我正在使用 Dev C++,但我总是收到链接器错误。dll.h 的代码是

#ifndef _DLL_H_
#define _DLL_H_

#if BUILDING_DLL
#define DLLIMPORT __declspec (dllexport)
#else 
#define DLLIMPORT __declspec (dllimport)
#endif 


class DLLIMPORT sum
{
  public:
    sum();
    void input();
    void add();
    void display();
    virtual ~sum(void);

  private:
          int x,y,res;

};


#endif 

and that of dllmain.cpp is
#include<iostream>
#include "dll.h"
#include <windows.h>
sum::sum()
{
 x=y=res=0;
}


sum::~sum()
{
}
void sum::input()
{
     std::cout<<"Enter two numbers ";
     std::cin>>x>>y;
}
void sum::add()
{
     res=x+y;
}
void sum::display()
{
     std::cout<<"The application in running under a dll file"<<std::endl;
     std::cout<<"The sum is "<<res<<std::endl;
}              

BOOL APIENTRY DllMain (HINSTANCE hInst     /* Library instance handle. */ ,
                       DWORD reason        /* Reason this function is being called. */ ,
                       LPVOID reserved     /* Not used. */ )
{
    switch (reason)
    {
      case DLL_PROCESS_ATTACH:
        break;

      case DLL_PROCESS_DETACH:
        break;

      case DLL_THREAD_ATTACH:
        break;

      case DLL_THREAD_DETACH:
        break;
    }

    /* Returns TRUE on success, FALSE on failure */
    return TRUE;
}

主机应用程序 (sample.cpp) 代码是

#include<iostream>
#include "dll.h"
using namespace std;
int main()
{
    sum s;
    s.input();
    s.add();
    s.display();
    system("pause");
    return 0;
}    

但我得到一个链接器错误说:

  [Linker error] undefined reference to `_imp___ZN3sumC1Ev@4' 
  [Linker error] undefined reference to `_imp___ZN3sum5inputEv@4' 
  [Linker error] undefined reference to `_imp___ZN3sum3addEv@4' 
  [Linker error] undefined reference to `_imp___ZN3sum7displayEv@4' 
  [Linker error] undefined reference to `_imp___ZN3sum7displayEv@4' 
  [Linker error] undefined reference to `_imp___ZN3sum7displayEv@4' 
  [Linker error] undefined reference to `_imp___ZN3sum7displayEv@4' 

我不知道该怎么办。我刚开始 dll 编程,但我坚持这一点。任何人都可以帮我解决这个问题吗?

4

2 回答 2

0

您的DLLIMPORT符号扩展为__declspec(dllexport)if BUILDING_DLLis #define'd。

因此,在您的 DLL 实现文件 ( dllmain.cpp) 中,您应该#define BUILDING_DLL #include "dll.h".

于 2012-11-04T11:02:59.320 回答
0

DLLIMPORT这样定义:

#if BUILDING_DLL
#define DLLIMPORT __declspec (dllexport)
#else
#define DLLIMPORT __declspec (dllimport)
#endif

但是您忘记BUILDING_DLL在包含以下内容之前在您的 dll 源文件中定义dll.h

#define BUILDING_DLL
#include "dll.h"

注意:您应该使用:

#ifdef BUILDING_DLL

代替

#if BUILDING_DLL

因为第一个是更多的自我记录。

于 2012-11-04T11:04:46.680 回答