1

The main objective with this question is to write an CMakeLists.txt to generate a dynamic library, "containing/linked" a static library.

Let me create the scenario:

  • My C++ code is written in mycode.cpp
  • In mycode.cpp, I call some functions from libthirdparty.a (static library)
  • I want to generate libmylib.so (shared library) to be dynamically linked by others
  • libmylib.so must to "contain" libthirdparty.a

My attempt to write this script is at the lines bellow:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -Werror -m64 -fPIC ")
add_executable(myapp mycode.cpp)
target_link_libraries(myapp thirdparty)
add_library(mylib SHARED myapp)

But of course this is not working and I would like some help to write it correctly.

3
  • Try target_link_libraries(mylib thirdparty) Commented Aug 9, 2018 at 19:26
  • where? before, after or in place of any other command? Commented Aug 9, 2018 at 19:29
  • After you do a add_library(mylib SHARED mycode.cpp) just add the line I previously suggested. The target needs to exist before you can specify its properties. Commented Aug 9, 2018 at 19:38

1 Answer 1

2

For now, let's remove the myapp and focus only on the library you are trying to create.

That said, here is what you could do

cmake_minimum_required(VERSION 3.12)

project(AwesomeLib)

include(GenerateExportHeader)

set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)

find_package(ThirdParty REQUIRED)

add_library(mylib SHARED mylib.cpp)
target_link_libraries(mylib PUBLIC ThirdParty)

# Note: If you library will be cross-platform, flag should be conditionally specified. Have a look at generator-expression
target_compile_options(mylib PRIVATE -Wall -Werror)

generate_export_header(mylib)

# TODO:
# * add install rules
# * generate config-file package
# * add tests

Notes:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.