C CPP文件作为模块
C++ cpp files as modules
对不起,如果我重复了其他问题,但我不知道该如何用谷歌搜索。我想为我的程序添加一些小模块化:某些.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;
相关文章:
- C++20 使用 Visual Studio 编译模块:不编译或导入 ixx 文件
- 如何将网络模块添加到 QT pro 文件中?
- 没有头文件如何使用c ++调用其他模块中的函数?
- 是否可以使用另一个lua文件中定义的表,该表在当前文件中不需要作为模块
- C++-在没有自定义.lib文件的情况下从Lua C模块调用Lua函数
- 链接节点本机模块中的提升库,对象文件需要替代库版本
- 如何使用 Apache C 模块登录到文件
- SystemC:单个 cpp 文件中的多个模块实现
- pybind11:属性错误:尝试从 py 文件运行函数时,模块'XXX'没有属性'YYY'
- 找不到旧版本Microsoft模块文件
- 在C++模块化编程中,如何组装.cpp和.h文件
- 如何将 Cython 生成的模块从 python 导入到 C/C++ 主文件?(C/C++编程)
- Python - 导入 c++ 模块接口 - 无法打开共享对象文件
- 我应该把Boost.Python的.so文件放在哪里,这样我就可以把它作为一个模块导入,以及我如何将它与Python 2
- SWIG:如何将 python 文件合并到 swig 生成的最终模块文件中
- 如何为模块化项目正确创建 CMake 文件
- 在C 中包括文件/模块
- C CPP文件作为模块
- 创建一个生成文件来构建切换的模块
- Clangs c++ Module TS支持:如何告诉clang++在哪里找到模块文件