After reading some articles on static and shared libs I think I know the difference but I still cannot figure out a way to fix my use case. I have the following project structure
Project
├── A
│ ├── A.cpp
│ ├── A.h
│ └── CMakeLists.txt
├── B
│ ├── CMakeLists.txt
│ └── B.cpp
├── CMakeLists.txt
in folder A
I have:
//content of A.h
#include <opencv2/opencv.hpp>
cv::Mat A_load_image(std::string file_path);
//content of A.cpp
#include "A.h"
cv::Mat A_load_image(std::string file_path) {
return cv::imread(file_path);
}
// content of CMakelists.txt in A
set(TARGET A)
add_library( ${TARGET} STATIC A.cpp )
target_include_directories(${TARGET} PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}
/path/to/opencv/include/folder )
link_directories( /path/to/opencv/lib/folder)
target_link_libraries( ${TARGET} PUBLIC libopencv_core.a )
then in my folder B
I have:
//content of B.cpp
#include "A.h"
cv::Mat B_load_image() {
return A_load_image("img.bmp");
}
// content of CMakelists.txt in B
set(TARGET B)
add_library(A STATIC IMPORTED)
set_target_properties(A PROPERTIES IMPORTED_LOCATION /PATH/TO/libA.a)
add_library(${TARGET} SHARED B.cpp)
target_include_directories(${TARGET} PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../A
/path/to/opencv/include/folder )
target_link_libraries(${TARGET} PUBLIC A libopencv_core.a)
And of course I have the CMakelists.txt file in the project root has:
cmake_minimum_required(VERSION 3.4.1)
add_subdirectory(B)
add_subdirectory(A)
I have questions below regarding this project.
- How to tell cmake to compile B first so that when I import B for A, it is already updated if any changes
- The above setup does not work as I got error when linking B: "cannot find -lopencv_core", I already used PUBLIC for linking A, I also tried to add
link_directories( /path/to/opencv/lib/folder)
to the CMakelists.txt forB
, but still not working. I believe "cannot find -lopencv_core" failed because it is looking for dynamic lib, e.g.,libopencv_core.so
rather than the static one. But why is that and how I force to link to the static lib?