我想这有点晚了,但这里有一个解决方案:
#! /bin/sh
tmpf=/tmp/musl.log
# Detect Musl C library.
libc=$(ldd /bin/ls | grep 'musl' | head -1 | cut -d ' ' -f1)
if [ -z $libc ]; then
# This is not Musl.
rm -f ${tmpf}
exit 1
fi
$libc >${tmpf} 2>&1
vstr=$(cat ${tmpf} | grep "Version" | cut -d ' ' -f2)
v_major=$(echo $vstr | cut -d '.' -f1)
v_minor=$(echo $vstr | cut -d '.' -f2)
v_patch=$(echo $vstr | cut -d '.' -f3)
rm -f ${tmpf}
echo "-D__MUSL__ -D__MUSL_VER_MAJOR__=${v_major} -D__MUSL_VER_MINOR__=${v_minor} -D__MUSL_VER_PATCH__=${v_patch}"
这个 shell 脚本会提取一些有趣的信息并打印出-D
友好的值,以便头文件/源文件可以从中受益。看,
$ ./detect-musl.sh
-D__MUSL__ -D__MUSL_VER_MAJOR__=1 -D__MUSL_VER_MINOR__=1 -D__MUSL_VER_PATCH__=24
请尽早在您的 Makefile 中调用它并相应地调整您的CFLAGS
。
该脚本执行ldd
脚本,获取musl
名称中包含的库,然后执行该库。所有 libc 库都是可执行的(因为它们实际上包含_start()
),甚至产生输出。通常,这是版本信息。例如,GNU 显示:
$ /lib/x86_64-linux-gnu/libc.so.6
GNU C Library (Ubuntu GLIBC 2.27-3ubuntu1) stable release version 2.27.
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.
Compiled by GNU CC version 7.3.0.
libc ABIs: UNIQUE IFUNC
For bug reporting instructions, please see:
<https://bugs.launchpad.net/ubuntu/+source/glibc/+bugs>.
并且, musl 显示了这一点:
$ /lib/ld-musl-x86_64.so.1
musl libc (x86_64)
Version 1.1.24
Dynamic Program Loader
Usage: /lib/ld-musl-x86_64.so.1 [options] [--] pathname [args]
我已经在 Alpine 和 Linux Mint 上测试了我的脚本,它似乎工作正常。
和你一样,我讨厌迂腐的意识形态阻碍实用性。如果您找到更好的解决方案,请随时发布。:)
编辑:在交叉编译的情况下,ldd
无法工作。在生成测试程序并读取其 ELF 链接然后检查其中是否包含musl libc
字符串时,需要进行一些额外的工作。有关详细信息,请参阅GitHub片段。