Punit Salian
Punit Salian

Reputation: 41

How do I link the library correctly using cmake?

I have laid out my project directory below,so when I do cmake build I get a linker error which I wasn't able to figure out. I get a linker error that LIBD cannot be found, although LIBB is successfully formed and APP executable only needs LIBB why is it throwing a linker error that it needs LIBD when trying to build APP?

|---CMakeLists.txt <==== add_subdirectory(source) , add_subdirectory(apps)

|---build

|---include
    |---a.h
    |---b.h

|---apps|   
    |---CMakeLists.txt
    |---apps.cpp              1] target_link_libraries(APP PUBLIC LIBB)   <==== linker error 
                                                                                 LIBD not found
  
|---source
|   |---CMakeLists.txt  ===>  1]link_directories(PATH TO LIBD)
                              2]target_link_libraries(LIBA public LIBC) <== successful
                              3]target_link_libraries (LIBB public LIBA LIBD) <== successful

    |---a.cpp
    |---b.cpp

|---lib
|   |---LIBD    <===== static library 

Upvotes: 2

Views: 200

Answers (1)

Botje
Botje

Reputation: 30807

link_directories is scoped to the file containing it, in your case source/CMakeLists.txt, so apps/CMakeLists.txt does not know where to find LIBD.

You should create an IMPORTED CMake target in the main CMakeLists.txt instead and link to that where you need it:

add_library(LIBD IMPORTED)
set_target_properties(LIBD PROPERTIES
    IMPORTED_LOCATION lib/LIBD.a)

Or, alternatively, you could repeat the link_directories statement in your apps/CMakeLists.txt.

Upvotes: 1

Related Questions