0

I'm working on a cmake project which include some submodules. I set them all static libs(a.lib、b.lib, etc. Set static: add_library(a STATIC src), ect.) and link them to the main library(main.lib), using target_link_libraries(main a b).
I write a test project which will link main.lib and call some functions in it. I thought it should be OK because all the sub libs are static linked. But there were many "unresolved external symbol" errors reported, it couldn't find symbols belong to a.lib and b.lib. It is fixed after I add a.lib/b.lib in link dir.
It works well on linux, main.a can be used alone.
Any ideas?

naichuans
  • 31
  • 7
  • From which project do you get the errors? Can you provide a CMakeLists for us to reproduce. What you are describing should work. Remember that you need to link in your test project main.lib and also a.lib b.lib etc. – RoQuOTriX Jul 21 '22 at 05:31
  • Remember that you need to link in your test project main.lib and also a.lib b.lib etc. =========== ==hi, @RoQuOTriX, I just doubt about that. Why should I link a.lib/b.lib? Its functions should already be included in the main.lib becase they are static linked? I know you are right but I can't understand that – naichuans Jul 21 '22 at 05:48
  • https://stackoverflow.com/questions/37924383/combining-several-static-libraries-into-one-using-cmake maybe have a look at this question. What you want to achieve is to merge the static libs – RoQuOTriX Jul 21 '22 at 05:54
  • Thank you very much, @RoQuOTriX. The post meet my requirement. Still I have a question: if a.lib have two APIs: api_a and api_b, while main.lib only called api_b. If I combine the libs, the useless api_a would also be include in the combined lib, right? – naichuans Jul 21 '22 at 06:07
  • This depends on the toolchain. I would guess that the microsoft linker would not include unused references at the linkage state but I don't have any reference for that. This idea also appiles for example if you have two unrelated functions in LIB_B and only use one. Then only the one function should be included in the executable. But this only works for static libs because for dynamic libraries you do not know in advance what is needed from the DLL and what not and you also cannot slice it of course. – RoQuOTriX Jul 21 '22 at 06:14
  • The probably simplest approach here would be to use `target_link_libraries(main PUBLIC a b)` resulting in every target linking `main` also being linked to `a` and `b`, no merging of static libs required. – fabian Jul 21 '22 at 17:34
  • Hi, @fabian, I have target_link_libraries settings in my cmakelists.txt, it works on linux(we need no other libs but main.lib), But not work on windows(vs2019). I'm really confused about that. – naichuans Jul 25 '22 at 00:59

0 Answers0