(转载的)
1、新建Win32工程,选择Dll,工程名叫MyDll
2、添加Header Files:testdll.h,内容如下
内容如下: [cpp] view plaincopyprint?
1. #ifndef TestDll_H_
2. #define TestDll_H_
3.
4. #ifdef MYDLL_EXPORTS
5. #define MYLIBDLL extern "C" _declspec(dllexport)
6. #else
7. #define MYLIBDLL extern "C" _declspec(dllimport)
8. #endif
9.
10. extern "C" 11. {
12. MYLIBDLL int Add(int plus1, int plus2); 13. };
14. #endif
3、添加Source Files:testdll.cpp,内容如下:
[cpp] view plaincopyprint?
1. #include "stdafx.h"
2. #include "testdll.h"
3. #include <iostream>
4. using namespace std
5.
6. int Add(int plus1, int plus2)
7. {
8. int add_result = plus1 + plus2;
9. return add_result;
10. }
4、选择编译类型为:Release (注意,之前我一直使用Debug模式就会遇到各种错误无法使用,为什么请知道的大侠赐教,不胜感激?)
5、编译输出.lib和.dll文件。
6、将testdll.h、MyDll.lib、MyDll.dll三个文件放在新建的目录libs中,并放在下一个工程的项目文件夹里(和 MyDllDemo.sln 同在一个文件夹下)。
===============================================
1.、新建Win32 Console工程,命名为MyDllDemo
2、修改MyDllDemo.cpp
文件内容如下:
[cpp] view plaincopyprint?
1. #include "stdafx.h"
2.
3. #include <iostream>
4. using namespace std;
5.
6. #include "testdll.h"
7. //#pragma comment(lib,"MyDll.lib")
8.
9. int main()
10. {
11. int a = 1;
12. int b = 2;
13. int c = Add(a,b);
14. printf("%d + %d = %d\n",a,b,c); 15.
16. getchar();
17. return 0;
18. }
3、配置头文件查找路径:
properties -> C/C++ -> General -> Additional Include Directories -> 输入libs的绝对目录,如 D:\sonikk\project\c++\console32\MyDllDemo\libs
4、配置.lib文件查找路径:
properties -> Linker -> General -> Additional Library Directories -> 输入libs的绝对目录,如 D:\sonikk\project\c++\console32\MyDllDemo\libs
5、配置要导入的.lib文件(和代码中使用 #pragma comment(lib,"MyDll.lib") 语句效果相同): properties -> Linker -> Input -> Additional Library Directories -> MyDll.lib
6、配置.dll文件查找目录:
将MyDll.lib放在MyDllDemo工程的Debug目录下,和编译生成的exe一起。 OK~