C CPP文件作为模块

C++ cpp files as modules

本文关键字:模块 文件 CPP      更新时间:2023-10-16

对不起,如果我重复了其他问题,但我不知道该如何用谷歌搜索。我想为我的程序添加一些小模块化:某些.CPP文件应编译为"模块"。主要的要求是,我应该能够通过在项目中添加新的.cpp文件来添加模块,而不会以任何方式更改其他文件。

通过动态加载库实现这一看法。主程序可以扫描所有.DLL文件的文件夹,加载每个文件夹,并从每个模块调用导出的"加载"符号。在Destructor中,主程序可以调用"卸载"符号,以便模块可以清理。

我想要相同的功能,但具有整体程序。是否有任何方法可以让.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_成为静态局部变量,以确保它首次访问之前是初始化的。

您可以使用从主应用程序(Singleton)暴露的注册接口更改现有代码的情况下将新的.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;