我用它Makefile
用GNU Make运行了一些测试,并检查了一些变量的来源和默认值:
define whatisit
$(info $(1) origin is ($(origin $(1))) and value is ($($(1))))
endef
$(call whatisit,CC)
$(call whatisit,CFLAGS)
结果如下:
$ make
CC origin is (default) and value is (cc)
CFLAGS origin is (undefined) and value is ()
$ # Environment
$ CC=clang CFLAGS=-Wall make
CC origin is (environment) and value is (clang)
CFLAGS origin is (environment) and value is (-Wall)
$ # Command line
$ make CC=clang CFLAGS=-Wall
CC origin is (command line) and value is (clang)
CFLAGS origin is (command line) and value is (-Wall)
如您所见,有两种类型的变量。这些类型在手册中定义。
第一组变量 ( AR
, AS
, CC
, ...) 具有default
值。第二组变量(ARFLAGS
, ASFLAGS
, CFLAGS
, ...)默认为空字符串(即undefined
)。
默认情况下,它们可以被环境或命令行覆盖。
设置undefined
变量的默认值
对于undefined
变量(以及其他用户变量),您只需使用?=
运算符设置一个默认值,该默认值可以被环境或命令行覆盖。
CFLAGS ?= -Wall -Wextra -Werror
设置default
变量的默认值
更改default
变量默认值的最佳方法是检查它们的来源并仅在需要时更改值。
ifeq ($(origin CC),default)
CC = gcc
endif
结论
Makefile
: _
ifeq ($(origin CC),default)
CC = gcc
endif
CFLAGS ?= -Wall -Wextra -Werror
define whatisit
$(info $(1) origin is ($(origin $(1))) and value is ($($(1))))
endef
$(call whatisit,CC)
$(call whatisit,CFLAGS)
最终结果:
$ make
CC origin is (file) and value is (gcc)
CFLAGS origin is (file) and value is (-Wall -Wextra -Werror)
$ # Environment
$ CC=clang CFLAGS=-Wall make
CC origin is (environment) and value is (clang)
CFLAGS origin is (environment) and value is (-Wall)
$ # Command line
$ make CC=clang CFLAGS=-Wall
CC origin is (command line) and value is (clang)
CFLAGS origin is (command line) and value is (-Wall)
可选的
您可以使用该MAKEFLAGS
变量来禁用内置隐式规则和内置变量设置。这边走:
MAKEFLAGS += -rR
这将清除许多默认设置(您可以使用 进行检查make -p
)。但default
变量(如CC
)仍将具有默认值。