我是新手。我正在开发一个C ++共享库,我希望它可以选择在支持或不支持某个特性(代码块)的情况下进行编译。换句话说,如何通过(或许)将参数传递给make命令来让用户选择是否使用该功能编译库?
例如,我需要用户能够这样做:
make --with-feature-x
我该怎么做?例如,我是否需要编写配置文件?或者我可以直接在我的Makefile中执行此操作吗?
答案 0 :(得分:11)
我相信以下方式应该有效。您在运行make
时定义环境变量。在Makefile中,检查环境变量的状态。根据状态,您可以定义在编译代码时将传递给g ++的选项。 g ++使用预处理阶段的选项来决定要包含在文件中的内容(例如source.cpp)。
make FEATURE=1
ifeq ($(FEATURE), 1) #at this point, the makefile checks if FEATURE is enabled
OPTS = -DINCLUDE_FEATURE #variable passed to g++
endif
object:
g++ $(OPTS) source.cpp -o executable //OPTS may contain -DINCLUDE_FEATURE
#ifdef INCLUDE_FEATURE
#include feature.h
//functions that get compiled when feature is enabled
void FeatureFunction1() {
//blah
}
void FeatureFunction2() {
//blah
}
#endif
检查是否传入FEATURE(作为任何值):
ifdef FEATURE
#do something based on it
else
# feature is not defined. Maybe set it to default value
FEATURE=0
endif