簡體   English   中英

C ++ cpp文件作為模塊

[英]C++ cpp files as modules

抱歉,如果我要重復其他問題,但是我不知道如何使用它進行搜索。 我想在程序中添加一些次要的模塊化:一些.cpp文件應編譯為“模塊”。 主要要求是我應該能夠僅通過向項目中添加新的.cpp文件來添加模塊,而無需以任何方式更改其他文件。

使用動態加載庫可以輕松實現這一目標。 主程序可以掃描某個文件夾中的所有.dll文件,加載每個文件並從每個模塊調用導出的“加載”符號。 在析構函數中,主程序可以調用“卸載”符號,以便模塊可以清理。

我想要相同但帶有整體程序。 .cpp文件有什么方法可以自己注冊,以便主程序可以在某個時候調用其init()函數? 還是要在主程序中找到所有此類模塊?

如何在Linux內核中完成? 我知道簡單地添加.c文件可以使它們以某種方式工作。

您可以在每個cpp文件中使用一個靜態虛擬變量,並通過lambda對其進行初始化和注冊。 瑣碎的例子:

// registration.h

void register_cpp (std::string name);
void print_cpps ();

// registration.cpp
namespace {
   std::vector<std::string> & names () {
      static std::vector<std::string> names_ {};
      return names_;
   }
}

void register_cpp (std::string name) {
   names ().push_back (name); // well, push_back(std::move (name)) would be more efficient
}

void print_cpps () {
    for (auto && name : names()) { std::cout << name << "\n"; }
}

// a.cpp

#include "registration.h"
static std::nullptr_t e = ([] () { register_cpp ("a"); return nullptr; }) ();

// b.cpp

#include "registration.h"
static std::nullptr_t e = ([] () { register_cpp ("b"); return nullptr; }) ();

// main.cpp
#include "registration.h"
int main () {
   print_cpps ();
   return 0;
}

我認為您需要names_是一個靜態局部變量,以確保在首次訪問它之前已對其進行了初始化。

您可以使用從主應用程序(單個)公開的注冊界面將新的.cpp文件添加到靜態鏈接的應用程序,而無需更改現有代碼。

就像是

App.h:

 struct IModule {
     virtual void init() = 0;
     virtual ~IModule() {}
 };

 class App {
 public:
      void registerModule(IModule* newModule); // Stores the interface
                                               // pointer of an additional
                                               // module
      static App& instance() {
           static App theInstance;
           return theInstance;
      }
 };

NewModule.cpp:

 #include "App.h"

 class NewModule : public IModule {
 public:
      void init();
 private:
      NewModule() {
          App::getInstance().registerModule(this);
      }

      static NewModule instance;
 };

 NewModule NewModule::instance;

暫無
暫無

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

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