【问题标题】:Passing parameter to Makefile to change compiled code将参数传递给 Makefile 以更改编译的代码
【发布时间】:2013-08-04 08:31:21
【问题描述】:

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

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

make --with-feature-x  

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

【问题讨论】:

标签: c++ makefile shared-libraries


【解决方案1】:

我相信以下方式应该可行。在运行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

source.cpp

#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

【讨论】:

  • 完美!非常感谢。你能否告诉我如何检查 FEATURE 是否首先被定义/通过?
  • 上面的 make ifeq 语法是错误的。它应该是ifeq ($(FEATURE),1)。至于您的问题,您需要提供更多详细信息。我不确定 maditya,但我不明白您的意思是 如何首先检查 FEATURE 是否已定义/通过
  • @MadScientist 你说得对,我是凭记忆写的,然后把它搞砸了。会修复。此外,我认为 OP 正在询问是否设置了变量(设置为任何值),我认为 ifdef 应该可以工作
  • @maditya 这就是我的想法,我曾尝试过 ifdef 并失败了,但现在我明白了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-26
  • 1970-01-01
  • 1970-01-01
  • 2018-04-07
  • 2011-05-07
  • 2015-10-19
相关资源
最近更新 更多