![](/img/trans.png)
[英]When using C++ modules, is the any reason to separate function declarations (.hpp files) from their definitions (.cpp files)?
[英]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.