静态库实现

Static library implementation

本文关键字:实现 静态      更新时间:2023-10-16

我正在C++中实现一个静态库。我遇到的问题是,在库附带的头文件中,包含了其他头文件。如何包装库,使这些文件不可见?例如,假设我有这样的代码:

//MyLib.h
#ifndef MyLib_h
#define MyLib_h    
class Math
{
public:
  // this method returns the mass of the Universe
  static double CalcMassOfTheUniverse();
}
#endif
//MyLib.cpp
#include MyLyb.h
double Math::CalcMassofTheUniverse()
{
  // do some complicated calculations here
  return result;
}

然后我发现,为了更容易地计算宇宙的质量,我必须有一个UniverseObject类型的变量:

//MyLib.h
#ifndef MyLib_h
#define MyLib_h
#include "UniverseObject.h"
class Math
{
  public:
    double string CalcMassOfTheUniverse();
  private:
    UniverseObject m_Universe; // used to calculate the mass
}
#endif
//MyLib.cpp
#include MyLib.h
double Math::CalcMassofTheUniverse()
{       
  // Use m_Universe to calculate mass of the Universe 
  return massOfTheUniverse;
}

问题是,现在我在头文件中包含了"UniverseObject.h"。我知道这是必要的,因为Math类使用了它,但有没有一种方法可以将类包装成用户不知道我使用了什么头等等?我之所以这么问,是因为只给人们一个标题和库,而不是一堆标题会更容易。

更容易[…]拥有UniverseObject 类型的变量

一个"宇宙"是一个eo-ipso的一个候选单光子

universe.h:

#ifndef UNIVERSE_H
#define UNIVERSE_H 1
// Singleton pattern
class Universe {
public:    
    static Universe& instance() noexcept {
        static Universe universe; // there shall be light
        return universe;          // now there is light; that's good
    }
    double guess_total_energy() const noexcept;
private:
    Universe() noexcept;
    ~Universe() noexcept;
    Universe(const Universe&) = delete;
    Universe(Universe&&) = delete;
    Universe& operator=(const Universe&) = delete;
    Universe& operator=(Universe&&) = delete;
};
#endif // ifndef UNIVERSE_H

universe.c++:

#include <iostream>
#include "universe.h"
Universe::Universe() noexcept {
    std::cout << "BANG! (Universe constructor called)" 
              << std::endl; 
}
Universe::~Universe() noexcept {
    std::clog << "Universe destructor called." 
              << std::endl; 
}
double 
Universe::guess_total_energy() const noexcept {
    return 0.;
}

main.c++:

#include <iostream>
#include "universe.h"
int main() {
    std::cout << "In the beginning..." << std::endl;
    // or whereever you need that instance
    Universe& universe = Universe::instance(); 
    std::cout << std::scientific 
              << universe.guess_total_energy() << "J guessed"
              << std::endl;
    return 0; // EXIT_SUCCESS;
}

编译:

g++-4.9 -std=c++11 -Wall -pedantic  main.c++ universe.c++
./a.out

输出:

    In the beginning...
    BANG! (Universe constructor called)
    0.000000e+00J guessed
    Universe destructor called.

正如您可以从输出中获得的那样,"Universe"对象是根据第一次需求创建的,并且在程序终止时也会被清理。