Dynamic Library Sample with CMake on Windows

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)
  1. -DB_EXPORTS to define B_EXPORT as __declspec(dllexport)
  2. 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)
  1. LINE#1 add additional include directory containing B.h
  2. 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)
  1. 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值