在VS中創建和使用DLL動態鏈接庫


VS中使用動態鏈接庫較GCC略微復雜

  • 在VS中新建工程時建立dll工程
  • 在dll工程的頭文件中加入如下宏
#ifdef DLL_IMPLEMENT_
#define DLL_APL __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif
  • __declspec(dllimport)和__declspec(dllexport)聲明了某一對象的導入/導出屬性

  • 在dll的實現文件頭部使用宏將其聲明為dll內部的實現

#define DLL_IMPLEMENT_
  • 如使用dll的工程和dll工程同屬一個解決方案,在解決方案的屬性中設置好工程的依賴關系,在使用dll的工程的屬性中設置好頭文件和庫文件的路徑,即可直接編譯運行,需要注意的是,VS編譯使用dll的程序時,依然需要該dll對應的lib文件,和gcc直接可以連接動態庫有所不同
  • 可以將一個dll的相關內容包含在一個命名空間里,由於命名空間的定義可以不連續,這樣也不會對實現和接口的分離造成什么麻煩

程序例子

DLL頭文件: DLLtest.h

#ifndef _TEST_H_
#define _TEST_H_

#ifdef DLL_IMPLEMENT_
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif

namespace dll
{
	int DLL_API add(const int &a, const int &b);
	int DLL_API sub(const int &a, const int &b);
	int DLL_API mul(const int &a, const int &b);
	int DLL_API div(const int &a, const int &b);
}

#endif

DLL實現文件:DLLtest.cpp

#define DLL_IMPLEMENT_
#include "test.h"

namespace dll
{
	int add(const int &a, const int &b)
	{
		return a + b;
	}

	int sub(const int &a, const int &b)
	{
		return a - b;
	}

	int mul(const int &a, const int &b)
	{
		return a * b;
	}

	int div(const int &a, const int &b)
	{
		return a / b;
	}
}

應用程序:entry.cpp

#include "test.h"
#include <iostream>

#pragma comment(lib, "DLLtest.lib")

using namespace std;
using namespace dll;

int main()
{
	int a, b;
	char c;
	while( cin >> a >> c >> b )
	{
		switch( c )
		{
		case '+':
			cout << add(a, b) << endl;
			break;
		case '-':
			cout << sub(a, b) << endl;
			break;
		case '*':
			cout << mul(a, b) << endl;
			break;
		case '/':
			cout << dll:: div(a, b) << endl;
			break;
		default:
			cout << '\"' << a << c << b << '\"' << "isn't a valid expression." << endl;
		}
	}
}

Written with StackEdit.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM