【问题标题】:gcc or g++ path search order on default directories when linking libraries链接库时默认目录上的 gcc 或 g++ 路径搜索顺序
【发布时间】:2017-06-07 00:51:23
【问题描述】:

我看过this的文章并了解到:

  1. 在命令行中使用-L 选项指定的目录在默认目录之前进行搜索。
  2. -L 中指定的目录按照它们在命令行中指定的顺序进行搜索。

问题是:默认目录有搜索顺序吗?

例如,如果我运行这个命令:

$ gcc -Xlinker --verbose  2>/dev/null | grep SEARCH | sed 's/SEARCH_DIR("=\?\([^"]\+\)"); */\1\n/g'  | grep -vE '^$'

(从this article复制的命令)

它在我的机器(Ubuntu 16.04、64 位、gcc 5.4.0)中在/usr/lib 之前打印出/usr/local/lib。在这种情况下,/usr/local/lib 会在 /usr/lib 之前被搜索到吗?

【问题讨论】:

    标签: c++ c gcc linker g++


    【解决方案1】:

    来自binutils ld manual 部分3.4.2 Commands Dealing with Files:

    SEARCH_DIR(路径)

    SEARCH_DIR 命令将路径添加到 ld 查找存档库的路径列表中。使用 SEARCH_DIR(path) 与在命令行上使用 `-L path' 完全一样(请参阅命令行选项)。如果两者都使用,则链接器将搜索这两个路径。首先搜索使用命令行选项指定的路径。

    所以,是的,因为默认目录是在 默认链接器脚本 中使用此 SEARCH_DIR() 命令给出的,它们将按照 SEARCH_DIR() 命令出现的顺序进行搜索。

    例如,在我的mingw 安装中,默认的链接器脚本是这样开始的:

    /* Default linker script, for normal executables */
    /* Copyright (C) 2014-2017 Free Software Foundation, Inc.
       Copying and distribution of this script, with or without modification,
       are permitted in any medium without royalty provided the copyright
       notice and this notice are preserved.  */
    OUTPUT_FORMAT(pei-i386)
    SEARCH_DIR("=/mingw32/i686-w64-mingw32/lib");
    SEARCH_DIR("=/mingw32/lib");
    SEARCH_DIR("=/usr/local/lib");
    SEARCH_DIR("=/lib");
    SEARCH_DIR("=/usr/lib");
    

    --> /usr/local/lib 中的库可以覆盖/lib 和/usr/lib 中的库,但不能覆盖mingw 本身提供的库。

    【讨论】:

    • 感谢您的回答!但我认为这个答案中的引用没有明确提到搜索顺序。它只是说Using SEARCH_DIR(path) is exactly like using '-L path'。我是否应该从这一行中推断出,知道-L 指定的路径会按照它们出现的顺序进行搜索,SEARCH_DIR() 的顺序也很重要?
    • @devnglee 你怎么理解一模一样?
    猜你喜欢
    • 2023-03-22
    • 2014-06-05
    • 2012-02-13
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多