#pragma once class CTest { public: CTest(void); public: ~CTest(void); public: int Add(int x, int y); int Square(int x); }; //函数的实现必须写在.cpp文件中,否则编译有错,说重复定义 int Max(int x, int y);
静态lib的实现文件: CPPLib->test.cpp
#include "StdAfx.h" #include "Test.h" CTest::CTest(void) { } CTest::~CTest(void) { } int CTest::Add(int x, int y) { return x+y; } int CTest::Square(int x) { return x*x; } int Max(int x, int y) { return x; }
client调用CPPLibClient->CPPibClient.cpp
#include "stdafx.h" //#include "test.h" //#include <windows.h> //#include <string> //#include <assert.h> //#include "../CppLib/test.h" //#pragma comment(lib,"../debug/CppLib.lib") //#pragma 使用法 //#include "test.h" //修改编译选项调用静态库 //需要修改:include的path,lib的path,和加入lib的名字,如下: //C++->General->additional include directories //Linker->General->additional library directories //linker->input->additional dependencies //不能动态加载静态的lib库 //HMODULE m_handle = LoadLibrary(L"../debug/CppLib.Lib"); //GetProcAddress(m_handle, "Max"); //FreeLibrary(m_handle); int _tmain(int argc, _TCHAR* argv[]) { CTest test; int a = test.Add(10,20); printf("the result is :%d/n",a); a = Max(10,20); printf("the result is :%d/n",a); return 0; }
#pragma once extern "C" _declspec(dllexport) int nCppDll; extern "C" _declspec(dllexport) int fnCppDll(void); extern "C" _declspec(dllexport) int Max(int a, int b); extern "C" _declspec(dllexport) int Min(int a, int b);
动态dll的实现:CPPDLL->test.cpp
#include "StdAfx.h" #include "Test.h" // This is an example of an exported variable int nCppDll=100; // This is an example of an exported function. int fnCppDll(void) { return 42; } int Max(int a, int b) { if(a>=b)return a; else return b; } int Min(int a, int b) { if(a>=b)return b; else return a; }
client的调用:cppclient->cppclient.cpp
#include "stdafx.h" #pragma comment(lib, "../debug/CppDll.lib") extern "C"int Max(int a,int b);//_declspec(dllimport) extern "C"int Min(int a,int b); //_declspec(dllimport) extern "C" _declspec(dllimport) int nCppDll; extern "C"int fnCppDll(void); //#include "test.h" //修改编译选项调用静态库 //需要修改:include的path,lib的path,和加入lib的名字,如下: //C++->General->additional include directories //Linker->General->additional library directories //linker->input->additional dependencies int _tmain(int argc, _TCHAR* argv[]) { int a; a =Min(8,10); printf("比较的结果为 %d/n",a); a= Max(8,10); printf("比较的结果为%d/n",a); printf("导出的变量:%d/n",nCppDll); a = fnCppDll(); printf("fnCppDll的结果:%d/n",a); return 0; }
上面演示了对一般变量和函数的导出的调用方法中的其中的2中,修改编译选项和pragma comment(),当使用pragma comment()的使用,应当注意: 使用#pragma隐式加载动态库 对于变量,必须申明且不能include头文件。extern "C" _declspec(dllimport) int nCppDll; 对于函数,或include头文件,或是申明。extern "C" int fnCppDll(void); 对于类,最好使用函数封装导出指针供使用。 参考:http://www.cppblog.com/mzty/archive/2006/07/24/10419.html