1 Dynamic Library Sample with CMake on Windows
1.1 Create Dynamic Library
CODE#1 dll[import|export]
#pragma 1.1.1.1.1.1.1 once
#if 1.1.2 defined(B_EXPORTS)
#define B_EXPORT __declspec(dllexport)
#else 1.1.2.0.1
#define B_EXPORT __declspec(dllimport)
#endif 1.1.2.0.1.1
CODE#2 sample exported function
extern B_EXPORT void sayHoo();
CODE#3 B/CMakeLists.txt
add_definitions(-DB_EXPORTS)
add_library(B SHARED B.cpp)
- -DB_EXPORTS to define
B_EXPORT
as__declspec(dllexport)
SHARED
in add_library
1.2 Create Executable using Dynamic Library
CODE#1 A/CMakeLists.txt
include_directories("${PROJECT_SOURCE_DIR}/B")
add_executable(A main.cpp)
target_link_libraries(A B)
- LINE#1 add additional include directory containing B.h
- LINE#3 link B.lib to resolve symbols of B
1.3 Change RUNTIME_OUTPUT_DIRECTORY
CODE#1 CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
project(SharedSample)
set (CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR})
add_subdirectory(B)
add_subdirectory(A)
- LINE#4 set CMAKE_RUNTIME_OUTPUT_DIRECTORY, so that to put A.exe and B.dll in the same directory (i.e. ${PROJECT_SOURCE_DIR})
1.4 SEE ALSO
commands: add_definitions, add_library
variables: CMAKE_RUNTIME_OUTPUT_DIRECTORY, PROJECT_BINARY_DIR