静态库的编写与使用

    xiaoxiao2025-01-05  12

    一.静态库的编写:

    1.Test_Lib.h

    #pragma once 函数申明 int Add(int a, int b); int Sub(int a, int b); int Mul(int a, int b); 类申明 #define STACK_INIT_SIZE 10 class Stack { public: Stack(int sz = STACK_INIT_SIZE); ~Stack(); public: bool IsFull()const; bool IsEmpty()const; public: bool Push(int x); bool Pop(); void Show()const; private: int *data; int capacity; int top; }; 2.Test_Lib.cpp

    #include <iostream> #include "Test_Lib.h" using namespace std; 函数实现 int Add(int a,int b) { return a+b; } int Sub(int a,int b) { return a-b; } int Mul(int a,int b) { return a*b; } 类实现 Stack::Stack(int sz) { capacity = sz > STACK_INIT_SIZE ? sz : STACK_INIT_SIZE; data = new int[capacity]; top = 0; } Stack::~Stack() { delete []data; data = NULL; capacity = top = 0; } bool Stack::IsFull()const { return top >= capacity; } bool Stack::IsEmpty()const { return top == 0; } bool Stack::Push(int x) { if(IsFull()) return false; data[top++] = x; return true; } bool Stack::Pop() { if(IsEmpty()) return false; top--; return true; } void Stack::Show()const { for(int i = top -1; i >= 0; --i){ cout<<data[i]<<endl; } } 运行后会在debug文件夹中产生一个 " Test_Lib.lib " 文件 二.静态库的使用: 将.h文件和.lib文件放入本文件中; 在mian.cpp中

    <span style="font-size:18px;">#include <iostream> #include "Test_Lib.h" using namespace std; #pragma comment(lib,"Test_Lib.lib") //显示包含静态库 void main() { int a = 10; int b = 20; cout<<Add(a,b)<<endl; cout<<Sub(a,b)<<endl; cout<<Mul(a.b)<<endl; Stack st; st.Push(1); st.Push(2); st.Push(3); st.Show(); }</span> 静态库一旦编译,可以到处运行。 因为.exe文件编译时,会把引用的静态库中的全部程序全部拷贝到本文件中,所以.exe可以到处运行。

    转载请注明原文地址: https://ju.6miu.com/read-1295179.html
    最新回复(0)