如何在任意系统上查找和测试编译器正在使用的*实际链接器?

时间:2014-02-06 14:32:12

标签: gcc linker clang ld icc

我需要从[some assembler |中传递一些对象另一个编译器|存档]直接到链接器。

但似乎路径上发现的ld是[破碎的]失踪|链接错误的ABI] 有时,我根本找不到ld

如何找到所使用的实际链接器,无论C编译器是什么,
[在Mac上|在Linux上在BSD |从配置脚本]?

1 个答案:

答案 0 :(得分:0)

我只需要弄清楚这一个。
这有点难,所以我想我会分享。

试一试:

#!/usr/bin/env sh

# 'main;' is the shortest C program possible (I think.).
# So it is compiled, linked, and written to /dev/null.
# So if the linker can't link, this should return 1.

for link in collect2 ld; do # Order matters, because of GCC.
 echo 'main;' | $CC -v -x c - -o /dev/null -\#\#\# 2>&1 | grep -q $link &&
 echo 'main;' | $CC -v -x c - -o /dev/null -\#\#\# 2>&1 | grep    $link |
 sed -e "s|\(.*$link\).*|\1|" -e 's/ //g' -e 's|"||' && break
done

# That should work on just about anything, and returns an absolute path,
# except with ICC. If we want to try to get an absolute path there too,
# we have to:

# If 'which' is missing, and it might not have an -s flag.
which="$(which which >/dev/null 2>&1)" || which=echo

$which "$(for link in collect2 ld; do
 echo 'main;' | $CC -v -x c - -o /dev/null -\#\#\# 2>&1 | grep -q $link &&
 echo 'main;' | $CC -v -x c - -o /dev/null -\#\#\# 2>&1 | grep    $link |
 sed -e "s|\(.*$link\).*|\1|" -e 's/ //g' -e 's|"||' && break
done)"

所以你可能刚刚说过,

  

来吧,没必要!就像which ld

一样

老实说,这在很大一部分时间里对我不起作用 它今天并不罕见,因为ld经常是一个包装器。

让我们测试一下,看看会发生什么:

#!/usr/bin/env sh

# On my Mac, nothing too special, I swear.
# Just a MacBook, Xcode, GCC from Homebrew, and one commercial compiler.


echo; $which ld; echo "...Not necessarily."; echo

for CC in cc gcc clang icc; do echo $c:
  for link in collect2 ld; do
    echo 'main;' | $CC -v -x c - -o /dev/null -\#\#\# 2>&1 | grep -q $link &&
    echo 'main;' | $CC -v -x c - -o /dev/null -\#\#\# 2>&1 | grep    $link |
       sed -e "s|\(.*$link\).*|\1|" -e 's/ //g' -e 's|"||' && break
   done

  which="$(which which 2>/dev/null 1>&1)" || which=echo
  $which "$(for link in collect2 ld; do
    echo 'main;' | $CC -v -x c - -o /dev/null -\#\#\# 2>&1 | grep -q $link &&
    echo 'main;' | $CC -v -x c - -o /dev/null -\#\#\# 2>&1 | grep    $link |
   sed -e "s|\(.*$link\).*|\1|" -e 's/ //g' -e 's|"||' && break
  done)"
  echo
done

返回:

/usr/bin/ld
...Not necessarily.

cc:
/Applications/Xcode51-Beta4.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld
/Applications/Xcode51-Beta4.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld

gcc:
/Users/Shared/usr/local/Cellar/gcc49/4.9-20140119/libexec/gcc/x86_64-apple-darwin13.1.0/4.9.0/collect2
/Users/Shared/usr/local/Cellar/gcc49/4.9-20140119/libexec/gcc/x86_64-apple-darwin13.1.0/4.9.0/collect2

clang:
/Applications/Xcode51-Beta4.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld
/Applications/Xcode51-Beta4.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld

icc:
ld
/usr/bin/ld