静态库实现

时间:2015-11-24 15:33:39

标签: c++ static-libraries

我正在用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类使用它,但有没有办法以这样的方式包装类,以至于用户不知道我使用什么标题等等?我问这个问题,因为给人们提供一个标题和库而不是一堆标题会更容易。

1 个答案:

答案 0 :(得分:1)

  

更容易拥有UniverseObject类型的变量

A"宇宙"是Singleton

的候选人

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.

你可以从输出中得到它,&#34;宇宙&#34; object是在第一次需求时创建的,也是在程序终止时清理的。