将参数传递给Makefile以更改已编译的代码

yel*_*yed 5 c++ makefile shared-libraries

我是新手.我正在开发一个C++共享库,我希望它可以选择在支持或不支持某个特性(代码块)的情况下进行编译.换句话说,如何通过(可能)将参数传递给make命令,使用户能够选择是否使用该功能编译库?

例如,我需要用户能够这样做:

make --with-feature-x  
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?例如,我是否需要编写配置文件?或者我可以直接在我的Makefile中执行此操作吗?

mad*_*tya 11

我相信以下方式应该有效.您在运行时定义环境变量make.在Makefile中,检查环境变量的状态.根据状态,您可以定义在编译代码时将传递给g ++的选项.g ++使用预处理阶段中的选项来确定要包含在文件中的内容(例如source.cpp).

命令

make FEATURE=1
Run Code Online (Sandbox Code Playgroud)

Makefile文件

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
Run Code Online (Sandbox Code Playgroud)

source.cpp

#ifdef INCLUDE_FEATURE 
#include feature.h

//functions that get compiled when feature is enabled
void FeatureFunction1() {
 //blah
}

void FeatureFunction2() {
 //blah
}

#endif
Run Code Online (Sandbox Code Playgroud)

检查是否传入FEATURE(作为任何值):

ifdef FEATURE
  #do something based on it
else
  # feature is not defined. Maybe set it to default value
  FEATURE=0
endif
Run Code Online (Sandbox Code Playgroud)