共享库中的依赖注入,该库是否需要目标文件? [英] Dependency injection in shared library, does the lib need object files?

查看:108
本文介绍了共享库中的依赖注入,该库是否需要目标文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我注入一个依赖关系,让它成为共享库中定义的类B中的类A的实例,共享库是否需要类A的目标文件进行链接? (Meant是库编译后的g ++链接阶段,而不是运行时的OS链接)

If I inject a dependency, let it be instance of class A, in a class B, which is defined in a shared library, will the shared library need the object files of class A for linkage? (Meant is the g++ linkage stage after the compilation of the library, not the OS linkage at runtime)

实际上我在linux上尝试过,但没有.所有平台都适用吗? (在这种情况下,请忽略符号可见性,除非必不可少)

Actually I tried this on linux and it does not. Is this true for all platforms? (Ignore symbol visibility in this case, unless essential)

a.h

#ifndef SOME_HEADERA_H
#define SOME_HEADERA_H
struct  A{
    void whoop();
};
#endif

a.cpp

#include <iostream>
#include "a.h"
void A::whoop (){
    std::cout << "A whooped."<< std::endl;
}

b.h

#ifndef SOME_HEADERB_H
#define SOME_HEADERB_H
class A;
struct  B {
    void whoopUsingA(A* a);
};
#endif

b.cpp

#include "b.h"
#include "a.h"
#include <iostream>
void B::whoopUsingA (A* a){
    std::cout << "B whoops A."<< std::endl;
    a->whoop();
}

main.cpp

#include "a.h"
#include "b.h"
int main (int argc, const char* argv[]) {
    A a;
    B b;
    b.whoopUsingA(&a);
    return 0;
}

推荐答案

答案既不是是"也不是否".

The answer is neither "Yes" nor "No".

您在这里有三个目标文件:
B(来自b.cpp,成为共享库)
A(来自a.cpp,可执行程序的一部分)
Main(来自main.cpp,是程序的另一部分)

You have three object files here:
B (from b.cpp, becomes a shared lib)
A (from a.cpp, a part of the executable program)
Main (from main.cpp, is the other part of the program)

重要的是要了解.h文件(至少在正常使用时)不会导致目标文件.在整个元组(一个cpp及其所有标头)成为一个目标文件之前,标头包含在Cpps中.

It's important to understand that .h files (at least when they're used normally) don't lead to object files. Headers are included in Cpps before the whole tuple (one cpp and all it's headers) become one object file.

因此,现在在b.h中,您拥有class A;,并希望使用此类的对象.如您所见,这还不够.为此,您需要的是文件a.h.但是您不需要需要a.cpp和/或它的目标文件,仅标头就足够了.

So, now in b.h, you have class A; and want to use objects of this class. As you've seen, this is not enough. What you need for this to work is the file a.h. But you do not need a.cpp and/or it's object file, the header alone is enough.

也很重要:
由于ABI等问题,如果满足以下条件,则可能不起作用:
a)对所有目标文件使用不同的编译器
b)您使用同一编译器的不同版本(某些组合有效,而其他组合则无效)
c)对于所有目标文件,某些特定的编译器标志并不相同
d)...

Also important:
Because of issues with the ABI etc., this may not work if:
a) You use not the same compiler for all object files
b) You use different versions of the same compiler (some combinations work, others don't)
c) Some specific compiler flags are not the same for all object files
d) ...

这篇关于共享库中的依赖注入,该库是否需要目标文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆