动态#include基于宏定义 [英] Dynamic #include based on macro definition
问题描述
我在写一个C ++应用程序,其中我想让开发人员选择在编译时为特定问题使用什么算法。这两种算法都实现为实现公共接口的C ++类,并且是互相替换的。他们都有一个.h和一个.cpp文件,并驻留在一个子目录(让我们称之为 impl /
)。
在我的Makefile中,我有这样的:
...
IMPL = default
...
binary:... impl / $(IMPL).o
...
impl /%。o:impl /%。 h impl /%。h
...
%o:%.cpp ...
$(CXX)$(CXXFLAGS)-DIMPL = $(IMPL)-c -o $ @ $ *。cpp
这个想法是用户应该能够输入 make binary IMPL = thatimpl
。
在任何想要使用用户选择的算法的文件中,
IImpl o = new IMPL();
但是,这需要包括所选实现的头文件。不幸的是,C ++需要 #include
后跟一个string
, ; libfile>
。您也可以此处的建议使用宏,但它需要宏的参数为文字字符串。如果我使用:
#define QUOTEME(M)#M
#define INCLUDE_FILE (M)QUOTEME(impl / ## M ##。h)
#include INCLUDE_FILE(IMPL)
$ b b
编译器将尝试包含文本字符串 impl / IMPL.h
,而不是将 IMPL
无论是传递给 make
然后到编译器。
任何指向我如何实现这将是非常欢迎!
您只需要添加一个额外的间接层,因为预处理器的工作方式。这应该:
#define QUOTEME(x)QUOTEME_1(x)
pre>
#定义QUOTEME_1(x)#x
#define INCLUDE_FILE(x)QUOTEME(impl / xh)
#include INCLUDE_FILE(IMPL)
I'm writing a C++ application in which I want to let the developer choose what algorithm to use for a particular problem at compile time. Both algorithms are implemented as C++ classes that implement a common interface, and are drop-in replacements for each other. They both have a .h and a .cpp file, and reside in a subdirectory (let's call it
impl/
).In my Makefile, I have something along the lines of this:
... IMPL = default ... binary: ... impl/$(IMPL).o ... impl/%.o: impl/%.cpp impl-interface.h impl/%.h ... %o: %.cpp ... $(CXX) $(CXXFLAGS) -DIMPL=$(IMPL) -c -o $@ $*.cpp
The idea is that the user should be able to type
make binary IMPL=thatimpl
.In whatever files wants to use the algorithm the user has chosen, I then do:
IImpl o = new IMPL();
However, this requires me to include the header file for the chosen implementation. Unfortunately, C++ requires
#include
to be followed by either a"string"
, a<libfile>
. You can also use a macro as suggested here, but it requires the argument to the macro to be a literal string. If I use:#define QUOTEME(M) #M #define INCLUDE_FILE(M) QUOTEME(impl/##M##.h) #include INCLUDE_FILE(IMPL)
The compiler will try to include the literal string
impl/IMPL.h
, rather than expandingIMPL
to whatever was passed tomake
and then to the compiler.Any pointers on how I might achieve this would be very welcome!
解决方案You just need to add an extra layer of indirection, because of the way the preprocessor works. This should do:
#define QUOTEME(x) QUOTEME_1(x) #define QUOTEME_1(x) #x #define INCLUDE_FILE(x) QUOTEME(impl/x.h) #include INCLUDE_FILE(IMPL)
这篇关于动态#include基于宏定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!