Dependency injection in shared library, does the l

2019-09-05 13:20发布

问题:

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)

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;
}

回答1:

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

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)

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.

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.

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) ...



标签: c++ linker