I have the following Project Structure:
\---mwe
| CMakeLists.txt
+---app
| CMakeLists.txt
| main.cpp
+---include
| \---mwe
| export.hpp
| my_lib.hpp
\---src
dummy.cpp
example_class.cpp
example_class.hpp
my_lib.cpp
I have the following CMakeLists.txt
:
cmake_minimum_required(VERSION 3.14)
if(CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR)
message(FATAL_ERROR "Do not build in-source. Please remove CMakeCache.txt and the CMakeFiles/ directory. Then build out-of-source.")
endif()
project("mwe" VERSION 1.0.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
option(BUILD_SHARED_LIBS "Build shared (dynamic) libraries." ON)
add_library(${PROJECT_NAME}_static STATIC include/${PROJECT_NAME}/export.hpp include/${PROJECT_NAME}/my_lib.hpp src/example_class.hpp src/example_class.cpp src/my_lib.cpp)
target_include_directories(${PROJECT_NAME}_static PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>"
PRIVATE "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src>")
set_target_properties(${PROJECT_NAME}_static PROPERTIES VERSION ${${PROJECT_NAME}_VERSION}
PUBLIC_HEADER "${${LIBRARY_NAME}_HDR}")
string (TOUPPER ${PROJECT_NAME} PROJECT_NAME_UPPER)
set_target_properties(${PROJECT_NAME}_static PROPERTIES COMPILE_FLAGS -D${PROJECT_NAME_UPPER}_STATIC)
if (MSVC)
set_target_properties(${PROJECT_NAME}_static PROPERTIES DEBUG_POSTFIX "d")
endif()
include(GenerateExportHeader)
string (TOUPPER ${PROJECT_NAME} PROJECT_NAME_UPPER)
generate_export_header(${PROJECT_NAME}_static
EXPORT_FILE_NAME ${CMAKE_CURRENT_SOURCE_DIR}/include/${PROJECT_NAME}/export.hpp
EXPORT_MACRO_NAME ${PROJECT_NAME_UPPER}_EXPORT
STATIC_DEFINE ${PROJECT_NAME_UPPER}_STATIC
)
add_library(${PROJECT_NAME} SHARED src/dummy.cpp)
add_library("Mwe::mwe" ALIAS ${PROJECT_NAME})
target_link_libraries(${PROJECT_NAME} PUBLIC ${PROJECT_NAME}_static)
add_subdirectory(app)
And the CMakeLists.txt
in the app
folder:
set(APP_TARGET_NAME ${PROJECT_NAME}_app)
add_executable(${APP_TARGET_NAME} main.cpp)
target_link_libraries(${APP_TARGET_NAME} PRIVATE Mwe::mwe)
I first create a static
library from all the sources of the Project.
I want to link to this static
library for my tests that i'm able to test also the private Part of the Library. (the function/classes which i don't want to export)
For the application i want to link to a shared
Library. Thats what the second Target is creating. Since i could not create a shared
Library without specifing the sources
i added an empty dummy.cpp
file. I then link that shared
Library to the previously created static
one.
The creation of both works quite well. But if i build the whole Project it gave me the following error when it tries to link the main.cpp
with the dll
:
LINK : fatal error LNK1104: Datei "..\Debug\mwe.lib" kann nicht geöffnet werden. [D:\projekte\mwe\build\app\mwe_app.vcxproj]