pro*_*eek 1 c++ windows dynamic-linking visual-studio
我有以下C++代码来制作DLL(Visual Studio 2010).
class Shape {
public:
Shape() {
nshapes++;
}
virtual ~Shape() {
nshapes--;
};
double x, y;
void move(double dx, double dy);
virtual double area(void) = 0;
virtual double perimeter(void) = 0;
static int nshapes;
};
class __declspec(dllexport) Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) { };
virtual double area(void);
virtual double perimeter(void);
};
class __declspec(dllexport) Square : public Shape {
private:
double width;
public:
Square(double w) : width(w) { };
virtual double area(void);
virtual double perimeter(void);
};
Run Code Online (Sandbox Code Playgroud)
我有__declspec,
class __declspec(dllexport) Circle
Run Code Online (Sandbox Code Playgroud)
我可以使用以下命令构建一个dll
CL.exe /c example.cxx
link.exe /OUT:"example.dll" /DLL example.obj
Run Code Online (Sandbox Code Playgroud)
当我试图使用该库时,
Square* square; square->area()
Run Code Online (Sandbox Code Playgroud)
我收到了错误消息.有什么不对或缺失?
example_unittest.obj : error LNK2001: unresolved external symbol "public: virtual double __thiscall ... Square::area(void)" (?area@Square@@UAENXZ)
在wengseng的回答之后,我修改了头文件,对于DLL C++代码,我添加了
#define XYZLIBRARY_EXPORT
Run Code Online (Sandbox Code Playgroud)
但是,我仍然有错误.
对于链接example.dll的主程序,我没有链接example.lib.
cl /MD /EHsc gtest_main.cc example_unittest.cc /I"./include" /link /libpath:"./lib" /libpath:"." gtest_md.lib example.lib /out:gtest_md_release.exe
Run Code Online (Sandbox Code Playgroud)
除此之外,一切正常.
在DLL中,我建议添加一个宏,并在预处理器中添加XYZLIBRARY_EXPORT:
#if defined(XYZLIBRARY_EXPORT) // inside DLL
# define XYZAPI __declspec(dllexport)
#else // outside DLL
# define XYZAPI __declspec(dllimport)
#endif // XYZLIBRARY_EXPORT
class XYZAPI Circle
Run Code Online (Sandbox Code Playgroud)
它将导出Circle类.
在EXE中,导入Circle类,而不添加预处理器,因为它将默认导入该类.