简体   繁体   English

加载静态库时的C ++执行功能

[英]C++ Executing functions when a static library is loaded

I need to register classes when the code is loading. 代码加载时,我需要注册类。 I implemented a solution which works great as long as the code is compiled in the app. 我实现了一个解决方案,只要在应用程序中编译代码,该解决方案就可以很好地工作。

But when the code is provided by a static library it doesn't work at all. 但是,当代码由静态库提供时,它根本不起作用。

I solved this problem in a fashion similar to this answer: https://stackoverflow.com/a/729028/171711 . 我以类似于以下答案的方式解决了这个问题: https : //stackoverflow.com/a/729028/171711

Currently I have something like: 目前我有类似的东西:

#define REGISTER(className)\
static const int __classDescriptor##className = MyRegister(#className, className::GetAllocator());

When used it looks like: 使用时看起来像:

//Foo.cpp

REGISTER(Foo);

Foo::Foo()
{
  ...
}

And I have in the logs: 我在日志中:

registered class:Foo

But when I created a static library and Foo is provided by the library the problem is that REGISTER(Foo); 但是当我创建一个静态库并且该库提供Foo时,问题是REGISTER(Foo); is never called. 从未被调用。

I have a complex loading system to allow scripts to use native C++ classes which is dependent on this behavior. 我有一个复杂的加载系统,允许脚本使用依赖于此行为的本机C ++类。 Is there a way to force the code in Foo.cpp to execute when the library is loaded? 有没有办法在加载库时强制执行Foo.cpp中的代码?


Edit : It seems my question is directly related to the one about static linking in Visual Studio . 编辑 :似乎我的问题与有关Visual Studio中的静态链接的问题直接相关。 It seems I have the same problem with my own libraries. 看来我自己的库也有同样的问题。 I noticed that some of the classes from the library are registered. 我注意到该库中的某些类已注册。 And they are only the ones which have their .h file included in my project. 而且,只有它们的.h文件包含在我的项目中。

So is there a way to execute code in a lib without linking to the .h file? 那么,有没有一种方法可以在lib中执行代码而不链接到.h文件?

Use the -all_load linker option to load all members of static libraries. 使用-all_load链接器选项可以加载静态库的所有成员。 Or for a specific library, use -force_load path_to_archive. 或对于特定的库,请使用-force_load path_to_archive。

In Xcode, you'll want to add these options under "Other Linker Flags" for your executable (not your static library). 在Xcode中,您需要为可执行文件(而不是静态库)在“其他链接器标志”下添加这些选项。

This fixed the problem for my static initialization functions. 这解决了我的静态初始化函数的问题。

The only way to initialize my classes descriptors before any other code relying on them is called is to initialize the library. 在调用任何其他依赖它们的代码之前,初始化我的类描述符的唯一方法是初始化库。

I added a function MyLibraryInit() which calls a function on each __classDescriptor##className to force the initialization of each descriptor. 我添加了一个函数MyLibraryInit() ,该函数在每个__classDescriptor##className上调用一个函数以强制初始化每个描述符。

Unfortunately it seems to be the most elegant approach I could find. 不幸的是,这似乎是我能找到的最优雅的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM