测试链接器标志的支持
Test the support of a linker flag
我需要测试对特定 linker 标志 (--no-undefined
) 的支持,然后才能最终将其作为 Makefile
配方的一部分。
这个 linker 标志 保证 在所有平台上都得到支持(事实上,它破坏了 macosx
link 阶段),因此只有在实际支持时才启用它很重要。
我倾向于 运行时间测试,这似乎比编译器/系统的静态列表更可取,后者更难以维护。
最好是 Makefile
中的 运行 测试,然后有条件地设置标志。
最可靠的测试是 linking 测试,即尝试实际 link 某事。这种测试取决于您是 link 通过编译器还是直接使用 linker。我的方法是创建一个通用模板来测试任意标志,这样它就可以在不同的地方重复用于不同的标志,例如:
$ cat Makefile
CHECK_CC_FLAGS := -Wl,--no-undefined -Wl,--whatever
CHECK_LD_FLAGS := --no-undefined --whatever
define check_cc_flag
$(shell echo 'int main() { return 0; }' | $(CC) $(1) -xc - 2>/dev/null && echo $(1))
endef
define check_ld_flag
$(shell $(LD) $(1) -e 0 /dev/null 2>/dev/null && echo $(1))
endef
# If linking with $(CC)
test: LDFLAGS += $(foreach flag,$(CHECK_CC_FLAGS),$(call check_cc_flag,$(flag)))
# If linking with $(LD)
test_ld: LDFLAGS += $(foreach flag,$(CHECK_LD_FLAGS),$(call check_ld_flag,$(flag)))
test_ld: test.o
$(LD) $(LDFLAGS) -o $@ $<
模板尝试 运行 编译器或 linker,如果成功(即以 0 退出),它将打印出标志,否则输出将为空。如果编译器 and/or link 表现不佳(return 失败尝试为 0),可能会更麻烦。
Ubuntu 20.04 LTS 上的实际输出:
$ make test
cc -c -o test.o test.c
cc -Wl,--no-undefined test.o -o test
$ make test_ld
ld --no-undefined -o test_ld test.o
ld: warning: cannot find entry symbol _start; defaulting to 0000000000401000
我需要测试对特定 linker 标志 (--no-undefined
) 的支持,然后才能最终将其作为 Makefile
配方的一部分。
这个 linker 标志 保证 在所有平台上都得到支持(事实上,它破坏了 macosx
link 阶段),因此只有在实际支持时才启用它很重要。
我倾向于 运行时间测试,这似乎比编译器/系统的静态列表更可取,后者更难以维护。
最好是 Makefile
中的 运行 测试,然后有条件地设置标志。
最可靠的测试是 linking 测试,即尝试实际 link 某事。这种测试取决于您是 link 通过编译器还是直接使用 linker。我的方法是创建一个通用模板来测试任意标志,这样它就可以在不同的地方重复用于不同的标志,例如:
$ cat Makefile
CHECK_CC_FLAGS := -Wl,--no-undefined -Wl,--whatever
CHECK_LD_FLAGS := --no-undefined --whatever
define check_cc_flag
$(shell echo 'int main() { return 0; }' | $(CC) $(1) -xc - 2>/dev/null && echo $(1))
endef
define check_ld_flag
$(shell $(LD) $(1) -e 0 /dev/null 2>/dev/null && echo $(1))
endef
# If linking with $(CC)
test: LDFLAGS += $(foreach flag,$(CHECK_CC_FLAGS),$(call check_cc_flag,$(flag)))
# If linking with $(LD)
test_ld: LDFLAGS += $(foreach flag,$(CHECK_LD_FLAGS),$(call check_ld_flag,$(flag)))
test_ld: test.o
$(LD) $(LDFLAGS) -o $@ $<
模板尝试 运行 编译器或 linker,如果成功(即以 0 退出),它将打印出标志,否则输出将为空。如果编译器 and/or link 表现不佳(return 失败尝试为 0),可能会更麻烦。
Ubuntu 20.04 LTS 上的实际输出:
$ make test
cc -c -o test.o test.c
cc -Wl,--no-undefined test.o -o test
$ make test_ld
ld --no-undefined -o test_ld test.o
ld: warning: cannot find entry symbol _start; defaulting to 0000000000401000