Walkthrough : Creating and Using a Dynamic Link Library

本文介绍如何用C++创建动态链接库(DLL),并演示如何在控制台应用程序中引用和使用该DLL。通过创建数学运算类库,展示了从新建项目到最终运行应用的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The original post of this article is available in this link:



In this walkthrough, you will create a dynamic link library (DLL) containing useful routines that can be used by other applications. Using DLLs is a great way to reuse code. Rather than re-implementing these routines in every program you create, you write them once and reference them from applications that need the functionality.

This walkthrough uses native C++. For a walkthrough using native C++ to create a static library, see Walkthrough: Creating and Using a Static Library. For a walkthrough using Visual C++ that targets the Common Language Runtime, see Walkthrough: Creating and Using a Managed Assembly.

This walkthrough covers the following:

  • Creating a new dynamic link library (DLL) project

  • Adding a class to the dynamic link library

  • Creating an application that references the dynamic link library

  • Using the functionality from the class library in the console application

  • Running the application

This topic assumes you understand the fundamentals of the C++ language.

To create a new dynamic link library (DLL) project

  1. From the File menu, select New and then Project….

  2. From the Project types pane, under Visual C++, select Win32.

  3. From the Templates pane, select Win32 Console Application.

  4. Choose a name for the project, such as MathFuncsDll, and enter it in the Name field. Choose a name for the solution, such as DynamicLibrary, and enter it in the Solution Name field.

  5. Press OK to start the Win32 application wizard. From the Overview page of the Win32 Application Wizard dialog, press Next.

  6. From the Application Settings page of the Win32 Application Wizard, under Application type, select DLL if it is available or Console application ifDLL is not available. Some versions of Visual Studio do not support creating a DLL project using wizards. You can change this later to make your project compile into a DLL.

  7. From the Application Settings page of the Win32 Application Wizard, under Additional options, select Empty project.

  8. Press Finish to create the project.

To add a class to the dynamic link library

  1. To create a header file for a new class, from the Project menu, select Add New Item…. The Add New Item dialog will be displayed. From the Categoriespane, under Visual C++, select Code. From the Templates pane, select Header File (.h). Choose a name for the header file, such as MathFuncsDll.h, and press Add. A blank file will be displayed.

  2. Add a simple class named MyMathFuncs to do common mathematical operations, such as addition, subtraction, multiplication, and division. The code should resemble the following:

    // MathFuncsDll.h
    
    namespace MathFuncs
    {
        class MyMathFuncs
        {
        public:
            // Returns a + b
            static __declspec(dllexport) double Add(double a, double b);
    
            // Returns a - b
            static __declspec(dllexport) double Subtract(double a, double b);
    
            // Returns a * b
            static __declspec(dllexport) double Multiply(double a, double b);
    
            // Returns a / b
            // Throws DivideByZeroException if b is 0
            static __declspec(dllexport) double Divide(double a, double b);
        };
    }
    
  3. Note the __declspec(dllexport) modifier in the method declarations above. These modifiers enable the method to be exported by the DLL so they can be used by other applications. For more information, see dllexport, dllimport.

  4. To create a source file for a new class, from the Project menu, select Add New Item…. The Add New Item dialog will be displayed. From the Categoriespane, under Visual C++, select Code. From the Templates pane, select C++ File (.cpp). Choose a name for the source file, such as MathFuncsDll.cpp, and press Add. A blank file will be displayed.

  5. Implement the functionality for MyMathFuncs in the source file. The code should resemble the following:

    // MathFuncsDll.cpp
    // compile with: /EHsc /LD
    
    #include "MathFuncsDll.h"
    
    #include <stdexcept>
    
    using namespace std;
    
    namespace MathFuncs
    {
        double MyMathFuncs::Add(double a, double b)
        {
            return a + b;
        }
    
        double MyMathFuncs::Subtract(double a, double b)
        {
            return a - b;
        }
    
        double MyMathFuncs::Multiply(double a, double b)
        {
            return a * b;
        }
    
        double MyMathFuncs::Divide(double a, double b)
        {
            if (b == 0)
            {
                throw new invalid_argument("b cannot be zero!");
            }
    
            return a / b;
        }
    }
    
  6. To build the project into a DLL, from the Project menu, select MathFuncsDll Properties…. From the left pane, under Configuration Properties, selectGeneral. From the right pane, change the Configuration Type to Dynamic Library (.dll). Press OK to save the changes.

    NoteNote

    If building from the command line, use the /LD compiler option to specify that the output file should be a DLL. For more information, see /MD, /MT, /LD (Use Run-Time Library).

  7. Compile the dynamic link library by selecting Build Solution from the Build menu. This creates a DLL that can be used by other programs. For more information on DLLs, see DLLs.

To create an application that references the dynamic link library

  1. To create an application that will reference and use the dynamic link library that was just created, from the File menu, select New and then Project….

  2. From the Project types pane, under Visual C++, select Win32.

  3. From the Templates pane, select Win32 Console Application.

  4. Choose a name for the project, such as MyExecRefsDll, and enter it in the Name field. Next to Solution, select Add to Solution from the drop down list. This will add the new project to the same solution as the dynamic link library.

  5. Press OK to start the Win32 Application Wizard. From the Overview page of the Win32 Application Wizard dialog, press Next.

  6. From the Application Settings page of the Win32 Application Wizard, under Application type, select Console application.

  7. From the Application Settings page of the Win32 Application Wizard, under Additional options, deselect Precompiled header.

  8. Press Finish to create the project.

To use the functionality from the class library in the console application

  1. After you create a new Console Application, an empty program is created for you. The name for the source file will be the same as the name you chose for the project above. In this example, it is named MyExecRefsDll.cpp.

  2. To use the math routines that were created in the dynamic link library, you must reference it. To do this, select References… from the Project menu. From the Property Pages dialog, expand the Common Properties node and select References. Then select the Add New Reference… button. For more information on the References… dialog, see References, Common Properties, <Projectname> Property Pages Dialog Box.

  3. The Add Reference dialog is displayed. This dialog lists all the libraries that you can reference. The Project tab lists all the projects in the current solution and any libraries they contain. From the Projects tab, select MathFuncsDll. Then select OK. For more information on the Add Reference dialog, see Add Reference Dialog Box.

  4. To reference the header files of the dynamic link library, you must modify the include directories path. To do this, from the Property Pages dialog, expand theConfiguration Properties node, then the C/C++ node, and select General. Next to Additional Include Directories, type in the path to the location of theMathFuncsDll.h header file.

  5. Dynamic link libraries are not loaded by the executable until runtime. You must tell the system where to locate MathFuncsDll.dll. This is done using thePATH environment variable. To do this, from the Property Pages dialog, expand the Configuration Properties node and select Debugging. Next toEnvironment, type in the following: PATH=<path to MathFuncsDll.dll file>, where <path to MathFuncsDll.dll file> is replaced with the actual location of MathFuncsDll.dll. Press OK to save all the changes made.

    NoteNote

    If you intend to run the executable from the command line rather than from within Visual Studio, then you must manually update the PATH environment variable from the command prompt as follows: set PATH=%PATH%;<path to MathFuncsDll.dll file>, where <path to MathFuncsDll.dll file> is replaced with the actual location of MathFuncsDll.dll.

  6. You can now use the MyMathFuncs class in this application. Replace the contents of MyExecRefsDll.cpp with the following code:

    // MyExecRefsDll.cpp
    // compile with: /EHsc /link MathFuncsDll.lib
    
    #include <iostream>
    
    #include "MathFuncsDll.h"
    
    using namespace std;
    
    int main()
    {
        double a = 7.4;
        int b = 99;
    
        cout << "a + b = " <<
            MathFuncs::MyMathFuncs::Add(a, b) << endl;
        cout << "a - b = " <<
            MathFuncs::MyMathFuncs::Subtract(a, b) << endl;
        cout << "a * b = " <<
            MathFuncs::MyMathFuncs::Multiply(a, b) << endl;
        cout << "a / b = " <<
            MathFuncs::MyMathFuncs::Divide(a, b) << endl;
    
        return 0;
    }
    
  7. Build the executable by selecting Build Solution from the Build menu.

To run the application

  1. Make sure MyExecRefsDll is selected as the default project. From the Solution Explorer, select MyExecRefsDll, and then select Set As StartUp Projectfrom the Project menu.

  2. To run the project, select Start Without Debugging from the Debug menu. The output should look like this:

    a + b = 106.4
    a - b = -91.6
    a * b = 732.6
    a / b = 0.0747475

To give more visual feeling of some details configuration, here it is . 


the following image shows how to change the output type of the project. (after this change, the project for MathFuncsDll will generate .dll)



after you create the MyExecRefDll project, you can add the reference to the project through the following way




After the project reference has been added, you will see the following item in the Project Reference




In order to use the header file , to get access to the  symbols from the dll file.





In order to debug the code, you will need to add the .dll to the environment path.




<think>我们正在处理用户关于如何创建或生成DLL文件(Windows开发)的问题。根据用户上一次的问题和我们的回答历史,用户可能已经了解了一些基本概念,现在需要具体的步骤。 根据系统指令,我们需要使用中文回答,并且对数学表达式使用正确的LaTeX格式(尽管本问题可能较少涉及数学公式,但若有则需遵守)。同时,我们需要生成相关问题,并在回答中自然地添加引用标识(如果引用了参考内容)。 参考站内引用: [^1]: 提到了使用Lab Windows/CVI创建DLL的步骤:选择构建目标类型为动态链接库,然后创建C文件并插入DllMain和DllEntryPoint。 [^2]: 提到了使用Clion配合CMakeLists打包成DLL的步骤,以及在不同环境中使用DLL的验证。 但是,用户的问题是关于如何创建或生成DLL文件,我们可以提供多种方法,包括使用Visual Studio、Clion(CMake)以及命令行方式(如使用gcc)等。 由于用户指定了Windows开发,我们将重点放在Windows平台上。 回答结构: 1. 介绍DLL(动态链接库)的基本概念。 2. 使用Visual Studio创建DLL(因为这是Windows开发最常用的工具)。 3. 使用Clion(CMake)创建DLL(参考引用[2])。 4. 使用命令行工具(如MinGW的gcc)创建DLL(可选)。 5. 总结。 注意:在代码块中,我们将使用正确的语法高亮。 同时,根据指令,我们需要生成相关问题。 开始回答:</think>### 如何创建或生成DLL文件(Windows开发) 动态链接库(DLL)是Windows系统中实现代码共享的核心组件。以下是三种主流创建方法: #### 方法1:使用Visual Studio(推荐) 1. **创建项目** - 打开VS → 新建项目 → 选择"动态链接库(DLL)"模板 - 配置项目名称和位置 2. **编写导出函数** ```cpp // MathLibrary.h #ifdef MATHLIBRARY_EXPORTS #define MATHLIB_API __declspec(dllexport) #else #define MATHLIB_API __declspec(dllimport) #endif extern "C" MATHLIB_API int Add(int a, int b); // 导出函数 ``` ```cpp // MathLibrary.cpp #include "MathLibrary.h" MATHLIB_API int Add(int a, int b) { return a + b; } ``` 3. **生成DLL** - 选择x64或x86目标平台 - 菜单栏 → 生成 → 生成解决方案 - 在`项目目录\x64\Debug\`下生成`.dll`和`.lib`文件 #### 方法2:使用CMake(跨平台方案) 1. **配置CMakeLists.txt** ```cmake add_library(MyDLL SHARED src/mylib.cpp ) set_target_properties(MyDLL PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON CXX_VISIBILITY_PRESET hidden ) ``` 2. **生成DLL** ```bash mkdir build && cd build cmake -G "Visual Studio 17 2022" .. cmake --build . --config Release ``` #### 方法3:使用MinGW命令行 ```bash g++ -shared -o mylib.dll mylib.cpp -Wl,--out-implib,libmylib.a ``` #### 🔑 关键注意事项 1. **函数导出** - 必须使用`__declspec(dllexport)`显式导出函数 - 建议使用`extern "C"`避免C++名称修饰 2. **依赖管理** - 发布时需同时提供`.dll`和头文件 - 使用`.lib`文件在编译时链接导入库 3. **调试技巧** - 使用`Dependency Walker`检查导出函数 - 通过`LoadLibrary`+`GetProcAddress`动态加载测试 > 示例工程参考:[MSDN官方DLL创建指南](https://docs.microsoft.com/zh-cn/cpp/build/walkthrough-creating-and-using-a-dynamic-link-library-cpp)[^1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值