我将举一些例子我自己的图书馆之一 https://github.com/mls-m5/matmath我已转换为支持旧样式标头和模块。
此示例适用于仅标头库,当我有一个库时,我将添加一个非标头库的示例。
仅标头/模块库
使导出成为可选。
就我而言,我已经定义了a file https://github.com/mls-m5/matmath/blob/master/include/matmath/export.h如果项目与模块一起使用,则使用添加导出的宏。
export.h https://github.com/mls-m5/matmath/blob/master/include/matmath/export.h
#pragma once
// Macros for handling compatability with/without modules
#ifdef matmath_use_modules
#ifndef matmath_export
#define matmath_export export
#endif
#else
#ifndef matmath_export
#define matmath_export
#endif
#endif
然后headers https://github.com/mls-m5/matmath/blob/master/include/matmath/vec.h库的定义几乎像往常一样,但进行了一些细微的调整,即使用导出宏而不是所需符号的导出关键字,并且所有包含都被删除。
vec.h https://github.com/mls-m5/matmath/blob/master/include/matmath/vec.h
// vec.h
#pragma once
#include "export.h"
#ifndef matmath_use_modules
#include <cmath>
#include <ostream>
#if __cplusplus >= 201103L
#include <tuple>
#endif
#include "pi.h"
#endif
matmath_export template <typename T>
class VecT {
public:
T x = 0, y = 0, z = 0;
constexpr VecT() = default;
...
};
然后,您可以在选择的模块中使用标头并激活正确的宏。
vec.cppm https://github.com/mls-m5/matmath/blob/master/modules/vec.cppm
module;
#include <cmath>
#include <ostream>
import matmath.pi;
export module matmath.vec;
#define matmath_use_modules
#include "matmath/vec.h"
// If your file has a regular cpp-file you could include that
// here in the same fashion
// #include "path/to/vec.cpp"
最后:在使用类时,您可以选择通过模块文件或头文件来使用项目(尽管将库的头文件和模块结合起来会带来很多麻烦)。
允许使用或不使用模块构建小型项目
如果您只想构建一个带有或不带有模块的小项目,您可以删除所有与导出相关的语句并将导入语句转换为包含。这种方法要求您对代码进行更改,或者至少有一个单独的步骤来创建代码的副本,而无需模块相关的代码。https://github.com/mls-m5/rym/blob/master/non-module-build.sh https://github.com/mls-m5/rym/blob/master/non-module-build.sh