Resolved: Cmake install nested static library target_link_library undefined reference

Question:

Install nested static library, and target_link_library not working
File structure:
main.cpp
HelloLib.cpp
HelloLib.h
CMakeLists.txt (HelloLib)
WorldLib.cpp
WorldLib.h
CMakeLists.txt (WorldLib)
Build and run, successfully print out Hello World!
Now I would like to make HelloLib as static library
Change CMakeLists.txt (HelloLib), install to /usr/lib and /usr/include
Run (make install) (CMAKE_INSTALL_PREFIX=/usr)
Static library (.a) should generate to /usr/lib/libHelloLib.a
Let’s test it, change CMakeLists.txt (root)
Then build, it give undefined reference error
What’s wrong with me? This can be successful with no nested library
What is the correct way to install nested static library?

Answer:

The issue here is not the install process but the fact that you link only to libHelloLib.a.
Your libHelloLib.a need the symbol in libWorldLib.a because libHelloLib.a is a static lib and so only contains its own symbol. It does not contains the symbol world that is defined in libWorldLib.a.
To make your project works, you need to install WorldLib and HelloLib and links against this two lib.
Or you can change HelloLib into a shared library. This way the libHelloLib.so will also contains the symbol of WorldLib.
You can also look at this Exported Target. It’s an install command that will create some FindXX.cmake file that you will be able to use with the find_package command. You also will be able to defined the dependency of your lib. But if you want that HelloLib stay a static library you will have to install WorldLib

If you have better answer, please add a comment about this, thank you!

Source: Stackoverflow.com