【问题标题】:Why Clang++ doesn't run the global object constructor in another static library?为什么 Clang++ 不在另一个静态库中运行全局对象构造函数?
【发布时间】:2015-07-01 01:09:58
【问题描述】:

我们有一个由clang++构建的库static_library.a,并且有一个文件bar.cpp包含一个全局对象Foo

但是当我们在App层Xcode项目中使用库时,却没有调用全局对象Foo构造函数。 (全局对象构造函数会做一些注册工作,并影响应用行为。)

我们认为翻译单元没有链接到可执行文件中。

//bar.cpp in static_library.a
class Foo
{
public:
   Foo()
   {
       std::cout << " constructor called" << std::endl;
   }
};

Foo a;
// <------If this function is called in the App layer project, the
// global constructor object will be called. 
Foo* getInstance()  
{
   return &a;
}

那么是否有任何标志可以控制这种行为?

【问题讨论】:

  • 你能试试-all_load吗?
  • 更好的控制方法是在 getInstance 函数中使用静态变量,只要调用该函数,您的对象就会被实例化
  • 但是很多翻译单元中有很多全局变量,所以我们不能一一列举。
  • @jtbandes,-all_load 有效。如果你能把它作为一个答案,我会把它作为正确的。谢谢。

标签: c++ ios xcode clang llvm


【解决方案1】:

您很可能需要-all_load 链接器标志。

This question 有更多详细信息。您可能还对-ObjC-force_load 感兴趣。

【讨论】:

  • 我在 google 中没有找到很多关于 -all_load 的信息。如果没有-all_load,接缝行为会违反 C++ 标准。那么为什么 clang++ 拥有它并将其设为默认值呢?
  • @ZijingWu:这是链接器的错,而不是clang的,这是因为该模块没有被其他(需要的)模块引用。
猜你喜欢
  • 2012-12-26
  • 1970-01-01
  • 2021-07-31
  • 1970-01-01
  • 2017-03-17
  • 1970-01-01
  • 2020-11-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多