动态#include基于宏定义 [英] Dynamic #include based on macro definition

查看:661
本文介绍了动态#include基于宏定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个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)
#定义QUOTEME_1(x)#x
#define INCLUDE_FILE(x)QUOTEME(impl / xh)

#include INCLUDE_FILE(IMPL)
pre>

直播示例


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 expanding IMPL to whatever was passed to make 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)

Live example

这篇关于动态#include基于宏定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆