C++学习笔记-使用静态库

静态库(.lib文件)是预编译的代码集合,在链接时会被完整地复制到最终的可执行文件中。理解如何正确配置和使用静态库是C++开发中的重要技能。

静态库的基本概念

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include "GLFW/glfw3.h"  // 第三方库的头文件

int main()
{
    int result = glfwInit();
    std::cout << "GLFW Init result: " << result << std::endl;
    
    if (result)
    {
        std::cout << "GLFW initialized successfully!" << std::endl;
        glfwTerminate();
    }
    else
    {
        std::cout << "Failed to initialize GLFW" << std::endl;
    }
    
    return 0;
}

配置静态库的步骤

1. 包含头文件目录

在Visual Studio中配置包含目录:

项目 -> 属性 -> C/C++ -> 常规 -> 附加包含目录 -> 添加路径
例如:$(SolutionDir)Dependencies\GLFW\include

2. 链接静态库文件

配置库文件和库目录:

项目 -> 属性 -> 链接器 -> 常规 -> 附加库目录 -> 添加路径
例如:$(SolutionDir)Dependencies\GLFW\lib-vc2022

项目 -> 属性 -> 链接器 -> 输入 -> 附加依赖项 -> 添加库文件
例如:glfw3.lib

3. 宏变量说明

  • $(SolutionDir):解决方案根目录
  • $(ProjectDir):当前项目目录
  • $(Configuration):当前配置(Debug/Release)
  • $(Platform):当前平台(x86/x64)

创建自己的静态库

数学库示例

MathLibrary.h

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#pragma once

namespace MathLib
{
    class Vector3
    {
    public:
        float x, y, z;
        
        Vector3();
        Vector3(float x, float y, float z);
        
        Vector3 operator+(const Vector3& other) const;
        Vector3 operator-(const Vector3& other) const;
        Vector3 operator*(float scalar) const;
        
        float Magnitude() const;
        Vector3 Normalize() const;
        float Dot(const Vector3& other) const;
        Vector3 Cross(const Vector3& other) const;
        
        void Print() const;
    };
    
    class Matrix4
    {
    private:
        float m_Data[16];
        
    public:
        Matrix4();
        Matrix4(float diagonal);
        
        static Matrix4 Identity();
        static Matrix4 Translation(const Vector3& translation);
        static Matrix4 Rotation(float angle, const Vector3& axis);
        static Matrix4 Scale(const Vector3& scale);
        
        Matrix4 operator*(const Matrix4& other) const;
        Vector3 operator*(const Vector3& vector) const;
        
        float& operator[](int index);
        const float& operator[](int index) const;
        
        void Print() const;
    };
    
    // 工具函数
    float ToRadians(float degrees);
    float ToDegrees(float radians);
    float Clamp(float value, float min, float max);
    float Lerp(float a, float b, float t);
}

MathLibrary.cpp

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include "MathLibrary.h"
#include <iostream>
#include <cmath>

namespace MathLib
{
    // Vector3 实现
    Vector3::Vector3() : x(0), y(0), z(0) {}
    
    Vector3::Vector3(float x, float y, float z) : x(x), y(y), z(z) {}
    
    Vector3 Vector3::operator+(const Vector3& other) const
    {
        return Vector3(x + other.x, y + other.y, z + other.z);
    }
    
    Vector3 Vector3::operator-(const Vector3& other) const
    {
        return Vector3(x - other.x, y - other.y, z - other.z);
    }
    
    Vector3 Vector3::operator*(float scalar) const
    {
        return Vector3(x * scalar, y * scalar, z * scalar);
    }
    
    float Vector3::Magnitude() const
    {
        return std::sqrt(x * x + y * y + z * z);
    }
    
    Vector3 Vector3::Normalize() const
    {
        float mag = Magnitude();
        if (mag > 0)
            return Vector3(x / mag, y / mag, z / mag);
        return Vector3();
    }
    
    float Vector3::Dot(const Vector3& other) const
    {
        return x * other.x + y * other.y + z * other.z;
    }
    
    Vector3 Vector3::Cross(const Vector3& other) const
    {
        return Vector3(
            y * other.z - z * other.y,
            z * other.x - x * other.z,
            x * other.y - y * other.x
        );
    }
    
    void Vector3::Print() const
    {
        std::cout << "(" << x << ", " << y << ", " << z << ")" << std::endl;
    }
    
    // Matrix4 实现
    Matrix4::Matrix4()
    {
        for (int i = 0; i < 16; ++i)
            m_Data[i] = 0.0f;
    }
    
    Matrix4::Matrix4(float diagonal)
    {
        for (int i = 0; i < 16; ++i)
            m_Data[i] = 0.0f;
        
        m_Data[0] = diagonal;   // [0,0]
        m_Data[5] = diagonal;   // [1,1]
        m_Data[10] = diagonal;  // [2,2]
        m_Data[15] = diagonal;  // [3,3]
    }
    
    Matrix4 Matrix4::Identity()
    {
        return Matrix4(1.0f);
    }
    
    float& Matrix4::operator[](int index)
    {
        return m_Data[index];
    }
    
    const float& Matrix4::operator[](int index) const
    {
        return m_Data[index];
    }
    
    void Matrix4::Print() const
    {
        for (int row = 0; row < 4; ++row)
        {
            for (int col = 0; col < 4; ++col)
            {
                std::cout << m_Data[row * 4 + col] << "\t";
            }
            std::cout << std::endl;
        }
    }
    
    // 工具函数实现
    float ToRadians(float degrees)
    {
        return degrees * 3.14159f / 180.0f;
    }
    
    float ToDegrees(float radians)
    {
        return radians * 180.0f / 3.14159f;
    }
    
    float Clamp(float value, float min, float max)
    {
        if (value < min) return min;
        if (value > max) return max;
        return value;
    }
    
    float Lerp(float a, float b, float t)
    {
        return a + (b - a) * Clamp(t, 0.0f, 1.0f);
    }
}

使用自定义静态库

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include "MathLibrary.h"

int main()
{
    using namespace MathLib;
    
    std::cout << "=== Vector3 Tests ===" << std::endl;
    
    Vector3 v1(1.0f, 2.0f, 3.0f);
    Vector3 v2(4.0f, 5.0f, 6.0f);
    
    std::cout << "v1: ";
    v1.Print();
    std::cout << "v2: ";
    v2.Print();
    
    Vector3 sum = v1 + v2;
    std::cout << "v1 + v2: ";
    sum.Print();
    
    Vector3 diff = v2 - v1;
    std::cout << "v2 - v1: ";
    diff.Print();
    
    Vector3 scaled = v1 * 2.0f;
    std::cout << "v1 * 2: ";
    scaled.Print();
    
    float dot = v1.Dot(v2);
    std::cout << "v1 · v2 = " << dot << std::endl;
    
    Vector3 cross = v1.Cross(v2);
    std::cout << "v1 × v2: ";
    cross.Print();
    
    std::cout << "v1 magnitude: " << v1.Magnitude() << std::endl;
    
    Vector3 normalized = v1.Normalize();
    std::cout << "v1 normalized: ";
    normalized.Print();
    
    std::cout << "\n=== Matrix4 Tests ===" << std::endl;
    
    Matrix4 identity = Matrix4::Identity();
    std::cout << "Identity Matrix:" << std::endl;
    identity.Print();
    
    std::cout << "\n=== Utility Functions ===" << std::endl;
    
    float degrees = 90.0f;
    float radians = ToRadians(degrees);
    std::cout << degrees << " degrees = " << radians << " radians" << std::endl;
    std::cout << radians << " radians = " << ToDegrees(radians) << " degrees" << std::endl;
    
    float clamped = Clamp(15.0f, 0.0f, 10.0f);
    std::cout << "Clamp(15, 0, 10) = " << clamped << std::endl;
    
    float lerped = Lerp(0.0f, 100.0f, 0.5f);
    std::cout << "Lerp(0, 100, 0.5) = " << lerped << std::endl;
    
    return 0;
}

静态库 vs 动态库

静态库特点

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*
静态库 (.lib/.a)
优点:
1. 部署简单:所有代码都在exe中,不需要额外文件
2. 加载速度快:不需要运行时加载
3. 版本一致:避免DLL地狱问题

缺点:
1. 文件大小:exe文件较大
2. 内存使用:多个程序使用同一库时,内存中有多份拷贝
3. 更新困难:库更新需要重新编译整个程序
*/

// 静态库链接示例
#pragma comment(lib, "MathLibrary.lib")  // 代码中指定链接库

int main()
{
    // 静态库的函数调用与普通函数调用完全相同
    MathLib::Vector3 v(1, 2, 3);
    v.Print();
    
    return 0;
}

条件编译和库配置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// 根据配置选择不同的库
#ifdef _DEBUG
    #pragma comment(lib, "MathLibrary_Debug.lib")
#else
    #pragma comment(lib, "MathLibrary_Release.lib")
#endif

// 根据平台选择不同的库
#ifdef _WIN64
    #pragma comment(lib, "MathLibrary_x64.lib")
#else
    #pragma comment(lib, "MathLibrary_x86.lib")
#endif

// 库的版本管理
namespace MathLib
{
    const int VERSION_MAJOR = 1;
    const int VERSION_MINOR = 2;
    const int VERSION_PATCH = 0;
    
    const char* GetVersion()
    {
        static char version[32];
        sprintf_s(version, "%d.%d.%d", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH);
        return version;
    }
}

int main()
{
    std::cout << "MathLibrary Version: " << MathLib::GetVersion() << std::endl;
    return 0;
}

跨平台静态库

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// 跨平台的库配置
#ifdef _WIN32
    // Windows特定代码
    #include <windows.h>
    #define PLATFORM_NAME "Windows"
#elif defined(__linux__)
    // Linux特定代码
    #include <unistd.h>
    #define PLATFORM_NAME "Linux"
#elif defined(__APPLE__)
    // macOS特定代码
    #include <unistd.h>
    #define PLATFORM_NAME "macOS"
#endif

namespace MathLib
{
    const char* GetPlatform()
    {
        return PLATFORM_NAME;
    }
    
    // 平台特定的高精度计时器
    class Timer
    {
    private:
#ifdef _WIN32
        LARGE_INTEGER m_Frequency;
        LARGE_INTEGER m_StartTime;
#else
        std::chrono::high_resolution_clock::time_point m_StartTime;
#endif
        
    public:
        Timer()
        {
#ifdef _WIN32
            QueryPerformanceFrequency(&m_Frequency);
            QueryPerformanceCounter(&m_StartTime);
#else
            m_StartTime = std::chrono::high_resolution_clock::now();
#endif
        }
        
        double GetElapsedSeconds()
        {
#ifdef _WIN32
            LARGE_INTEGER currentTime;
            QueryPerformanceCounter(&currentTime);
            return (double)(currentTime.QuadPart - m_StartTime.QuadPart) / m_Frequency.QuadPart;
#else
            auto currentTime = std::chrono::high_resolution_clock::now();
            auto duration = std::chrono::duration_cast<std::chrono::microseconds>(currentTime - m_StartTime);
            return duration.count() / 1000000.0;
#endif
        }
    };
}

最佳实践

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// 1. 使用命名空间避免命名冲突
namespace MyCompany::Graphics
{
    class Renderer
    {
        // 实现...
    };
}

// 2. 提供C接口以增强兼容性
extern "C"
{
    // C接口函数
    int MathLib_Vector3_Create(float x, float y, float z);
    void MathLib_Vector3_Destroy(int handle);
    float MathLib_Vector3_Magnitude(int handle);
}

// 3. 错误处理
namespace MathLib
{
    enum class ErrorCode
    {
        Success = 0,
        InvalidParameter,
        OutOfMemory,
        DivisionByZero
    };
    
    class Exception
    {
    private:
        ErrorCode m_Code;
        std::string m_Message;
        
    public:
        Exception(ErrorCode code, const std::string& message)
            : m_Code(code), m_Message(message) {}
            
        ErrorCode GetCode() const { return m_Code; }
        const std::string& GetMessage() const { return m_Message; }
    };
}

// 4. 配置和初始化
namespace MathLib
{
    struct Config
    {
        bool enableLogging = false;
        bool enableAssertions = true;
        float epsilon = 1e-6f;
    };
    
    bool Initialize(const Config& config = Config{});
    void Shutdown();
    const Config& GetConfig();
}

总结

  1. 静态库配置:需要正确设置包含目录和库目录,链接对应的.lib文件
  2. 静态库特点:代码会被完整复制到exe中,部署简单但文件较大
  3. 宏变量:$(SolutionDir)表示解决方案目录,$(ProjectDir)表示项目目录
  4. 最佳实践:使用命名空间、提供版本信息、考虑跨平台兼容性
  5. 与动态库对比:静态库速度更快,动态库文件更小,各有优劣
updatedupdated2025-09-202025-09-20