Giuseppe Pes
Giuseppe Pes

Reputation: 7912

Cmake Shared library

I am learning CMake but I am struggling to understand how to link a binary file to a shared library and then install these files in a release folder.

These is the structure of my project:

├── CMakeLists.txt
├── build
├── main
│   ├── CMakeLists.txt
│   └── main.cpp
├── release
|_______bin 
│   ├── include
│   │   └── math.h
│   └── lib
│       └── libmathLib.dylib
└── shared_lib
    ├── CMakeLists.txt
    ├── include
    │   └── math.h
    └── src
        └── math.cpp

In the root CMakeLists.txt I've defined the project settings and the subdirectory.

Root CMakeLists.txt:

cmake_minimum_required(VERSION 3.1)

project (Math)
set(CMAKE_BUILD_TYPE Release)

set(MAKE_INCLUDE_CURRENT_DIR ON)

ADD_SUBDIRECTORY(shared_lib)
ADD_SUBDIRECTORY(main)

Main CMakeLists.txt:

add_executable(main main.cpp)
TARGET_LINK_LIBRARIES(main LINK_PUBLIC mathLib)

Math lib ( shared lib )

include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)

add_library(mathLib SHARED src/math.cpp)

install(TARGETS mathLib DESTINATION /Users/giuseppe/development/cmake/release/lib LIBRARY NAMELINK_ONLY)
install(FILES include/math.h DESTINATION /Users/giuseppe/development/cmake/release/include)

When I build the project with Make, it doesn't link main.o to the shared library. Error :

Scanning dependencies of target mathLib
[ 50%] Building CXX object shared_lib/CMakeFiles/mathLib.dir/src/math.cpp.o
Linking CXX shared library libmathLib.dylib
[ 50%] Built target mathLib
Scanning dependencies of target main
[100%] Building CXX object main/CMakeFiles/main.dir/main.cpp.o
/Users/giuseppe/development/cmake/main/main.cpp:8:12: error: use of undeclared identifier 'sum'
  count << sum(5,6) << endl;
           ^
1 error generated.
make[2]: *** [main/CMakeFiles/main.dir/main.cpp.o] Error 1
make[1]: *** [main/CMakeFiles/main.dir/all] Error 2
make: *** [all] Error 2 

Release phase:

How can I make sure that the builds in the bin folder within the release folder use the shared lib in 'path/release/lib'? Possibly using a relative path such as '../lib/' ?

Upvotes: 1

Views: 972

Answers (1)

HeyYO
HeyYO

Reputation: 2073

You must add include directory for library to main/CMakeLists.txt. Adding it to shared_lib/CMakeLists.txt is not enough. Try this line:

include_directories("../shared_lib/include")

Upvotes: 0

Related Questions