【问题标题】:How does the -u option for ld work and when is it useful?ld 的 -u 选项如何工作以及何时有用?
【发布时间】:2014-09-10 03:00:22
【问题描述】:

我正在从ld 的人那里复制粘贴section :-

-u symbol
--undefined=symbol
  Force symbol to be entered in the output file as an undefined symbol. Doing this
  may,for example, trigger linking of additional modules from standard libraries.
  `-u' may be       repeated with different option arguments to enter additional
  undefined symbols.

如何实际使用此选项?就像我如何在我的源代码中触发附加模块的链接一样,这个选项什么时候真正有用?

【问题讨论】:

  • 这是一个 c++ 问题吗?
  • 我在找一个c++源代码示例
  • 我能找到的唯一附加信息是This option is equivalent to the EXTERN linker script command.,但关于该命令的信息是相同的,但需要注意它等同于-u

标签: c++ linker ld linker-flags


【解决方案1】:

这对于从静态库中提取目标文件很有用,否则代码中不会引用该目标文件。与静态库链接时,链接器仅使用其中满足未定义符号的对象。

这个选项没有很多实际的用例。链接一个原本未被引用的对象通常是没有意义的。据推测,如果它有用,它会在某处被引用。因此,包含它肯定会产生一些奇怪的副作用。

我可以给您的唯一真实示例是在 Windows 下使用 Microsoft 链接器的类似选项。我想把 DirectX 错误信息库(DXERR.LIB)转成 DLL,所以我使用了类似下面的命令:

link /machine:ix86 /dll /out:dxerr.dll /base:0x400000
    /include:_DXGetErrorStringA@4 /export:_DXGetErrorStringA@4
    /include:_DXGetErrorStringW@4 /export:_DXGetErrorStringW@4
    dxerr.lib mscvrt.lib user32.lib kernel32.lib 

/include 开关等效于 ld 的 -u 选项。如果我不考虑这些开关,我会得到一个没有从中导出任何函数的空 DLL。

【讨论】:

    【解决方案2】:

    我发现了一个有趣的用例示例。虽然 Ross 对 DLL 提出了很好的观点,但下面是如何使用 -u 选项的方法。

    a.cpp :-

    class A {
     public:
      static int init() {
        Factory::getInstance()->addObject(new A());
        return 0;
      }
    };
    int linker_a = A::init();
    

    Factory.cpp :-

    class Factory {
     public:
      Factory* getInstance() { return _instance; }
      void addObject(void* obj) { objects_.push_back(obj); }
     private:
      vector<void*> objects_;
      static Factory* _instance;
    };
    

    main.cpp :-

    #include "Factory.h"
    
    int main() {
    }
    

    现在当我们链接时,我们可以根据是否将 -u 链接器_a 传递给 ld 的命令行来选择是否将 A 对象添加到工厂。如果我们在命令行中传递它,A 的一个实例将被添加到工厂,否则它不会。

    这允许 main.cpp 和 Factory.{cpp,h} 的开发独立于 A.{cpp,h} (即 Factory.cpp 不必为了添加 A 的实例而包含 Ah到它的对象列表)。

    所以附加模块(“A”)的链接是由链接器标志 -u 触发的。

    非常简洁的功能!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-28
      • 2017-06-15
      • 2020-11-15
      • 1970-01-01
      • 2017-07-24
      • 2022-09-30
      • 2011-10-27
      相关资源
      最近更新 更多