windows创建和调用静态库
// MathFuncsLib.h namespace MathFuncs { class MyMathFuncs { public: // Returns a + b static double Add(double a, double b); // Returns a - b static double Subtract(double a, double b); // Returns a * b static double Multiply(double a, double b); // Returns a / b static double Divide(double a, double b); }; }
// MathFuncsLib.cpp // compile with: cl /c /EHsc MathFuncsLib.cpp // post-build command: lib MathFuncsLib.obj #include "MathFuncsLib.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) { return a / b; } }
调用静态库
// MyExecRefsLib.cpp // compile with: cl /EHsc MyExecRefsLib.cpp /link MathFuncsLib.lib #include <iostream> #include "MathFuncsLib.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; }
windows创建和调用动态库
// MathLibrary.h - Contains declaration of Function class #pragma once #ifdef MATHLIBRARY_EXPORTS #define MATHLIBRARY_API __declspec(dllexport) #else #define MATHLIBRARY_API __declspec(dllimport) #endif namespace MathLibrary { // This class is exported from the MathLibrary.dll class Functions { public: // Returns a + b static MATHLIBRARY_API double Add(double a, double b); // Returns a * b static MATHLIBRARY_API double Multiply(double a, double b); // Returns a + (a * b) static MATHLIBRARY_API double AddMultiply(double a, double b); }; }
// MathLibrary.cpp : Defines the exported functions for the DLL application. // Compile by using: cl /EHsc /DMATHLIBRARY_EXPORTS /LD MathLibrary.cpp #include "stdafx.h" #include "MathLibrary.h" namespace MathLibrary { double Functions::Add(double a, double b) { return a + b; } double Functions::Multiply(double a, double b) { return a * b; } double Functions::AddMultiply(double a, double b) { return a + (a * b); } }
调用动态库
// MathClient.cpp : Defines the entry point for the console application. // Compile by using: cl /EHsc /link MathLibrary.lib MathClient.cpp #include "stdafx.h" #include <iostream> #include "MathLibrary.h" using namespace std; int main() { double a = 7.4; int b = 99; cout << "a + b = " << MathLibrary::Functions::Add(a, b) << endl; cout << "a * b = " << MathLibrary::Functions::Multiply(a, b) << endl; cout << "a + (a * b) = " << MathLibrary::Functions::AddMultiply(a, b) << endl; return 0; }