簡體   English   中英

使用庫將庫包含與程序分離

[英]Separating Library Includes From Program Using Library

我正在創建一個DLL庫,它將導出一些要在其他C ++項目中使用的功能。 在我的庫中,我使用的是預編譯頭文件以及Boost ASIO。 但是,我想知道是否有可能在庫本身中包含所有與ASIO相關的內容,以便其他程序不需要包含它們。 例如:

stdafx.h(庫):

#pragma once

#include "targetver.h"

#define WIN32_LEAN_AND_MEAN

#include <Windows.h>
#include <WinSock2.h>
#include <iostream>
#include <string.h>

#pragma comment(lib, "ws2_32")

#include <boost/asio.hpp>

Client.h(庫):

#pragma once

#ifdef LIB_EXPORTS
#define LIB_API __declspec(dllexport)
#else
#define LIB_API __declspec(dllimport)
#endif

using boost::asio::ip::tcp;

namespace TestLib {
    class Client {
        boost::asio::io_service io_service_;
        tcp::resolver resolver_;
        tcp::socket socket_;

    public:
        LIB_API Client();

        LIB_API bool Connect(const std::string& szHost, const std::string& szPort);

        virtual ~Client();
    };
}

但是,在使用該庫的程序中,我希望能夠包含Client.h而不必包含Boost ASIO。 因為我包含了此標頭,但沒有包含Boost ASIO,所以我在Client.h中遇到了所有引用Boost工具的行的錯誤,例如using語句和三個私有成員變量。

我如何以這種方式創建庫,例如,我的其他程序僅需要包含Client.h?

我已經使用Anon Mail的建議解決了我的問題。 解決方法如下:

Client.h(庫):

#pragma once

#ifdef LIB_EXPORTS
#define LIB_API __declspec(dllexport)
#else
#define LIB_API __declspec(dllimport)
#endif

namespace TestLib {
    class Client {
        struct Imp;
        std::unique_ptr<Imp> imp_;

    public:
        LIB_API Client();

        LIB_API bool Connect(const std::string& szHost, const std::string& szPort);

        LIB_API virtual ~Client();
    };
}

Client.cpp(庫):

namespace TestLib {
    struct Client::Imp {
        Client::Imp() : 
            io_service_(new boost::asio::io_service()), 
            resolver_(new tcp::resolver(*io_service_)),
            socket_(new tcp::socket(*io_service_)) {

        }

        std::shared_ptr<boost::asio::io_service> io_service_;
        std::shared_ptr<tcp::resolver> resolver_;
        std::shared_ptr<tcp::socket> socket_;
    };

    Client::Client() : imp_(new Imp) {
    }

    bool Client::Connect(const std::string& szHost, const std::string& szPort) {
        tcp::resolver::query query(szHost, szPort);

        tcp::resolver::iterator endpoint_iter = imp_->resolver_->resolve(query);

        boost::asio::connect(*imp_->socket_, endpoint_iter);

        return true;
    }
}

如果我使用了錯誤類型的指針,請原諒我。 此解決方案的任何指導將不勝感激!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM