c++ undefined references with static library

后端 未结 5 1441
青春惊慌失措
青春惊慌失措 2020-12-02 09:55

I\'m trying to make a static library from a class but when trying to use it, I always get errors with undefined references on anything. The way I proceeded was creating the

5条回答
  •  臣服心动
    2020-12-02 10:32

    This is an issue how the linker optimizes the output code. Lets assume we have an executable that uses two libraries: Lib_A and Lib_B. Lib_A depends on Lib_B The Lib_A defines symbols: Lib_A1 and Lib_A2, and the Lib_B defines symbol Lib_B1 and Lib_B2. Now lets assume that the executable uses only symbol Lib_A1, and Lib_A1 uses symbol Lib_B1 which is defined in Lib_B. Symbol Lib_B1 is never used in the executable.

    1. In case of windows, the linker works like this: I have executable with two which uses some libs and all symbols used in executable and all libs are lib_A1 and lib_B1. Thus I will need these two symbols, and the rest is unnecessary. I will undefine lib_A2 and lib_B2
    2. In case of linux if you link Lib_B before Lib_A like this: g++ .... -lLib_B -lLib_A The linker works like this: I have executable that first links Lib_B. I do not see that the executable uses symbol Lib_B1 nor Lib_B2. They are unnecesary, thus I will undefine them. Later the linker see. Oh I have another library Lib_A. I can see that executable uses symbol Lib_B1. I will keep it and undefine unused symbol Lib_B2. It does not see that Lib_B1 uses Lib_A1, Which is already undefined.
    3. In case of linux if you link Lib_A before Lib_B like this: g++ ... -lLib_A -lLib_B The linker works like this: I have executable that first links Lib_A. Oh, I can see that executable uses Lib_A1. I will keep them and undefine Lib_A2. Later it can see. Oh I have another library Lib_B. I can see that now executable with already linked symbols, uses Lib_B1, I will keep them. As a result it keeps Lib_B1 and Lib_A1, and undefined Lib_B2 and Lib_A2.

提交回复
热议问题