Windows下使用CMakeLists生成动态库/静态库
引言
网上关于此主题的教程不少,但真正能使用的较少,windows下很多根本跑不通。本文提供一个可用demo.
一、代码
假设当前目录为currentDir。
头文件放在currentDir/include/shared目录下:
// include/shared/Hello.h
#ifndef __HELLO_H__
#define __HELLO_H__
class __declspec(dllexport) Hello
{
public:
void print();
};
#endif
源文件放在currentDir/src目录下:
// src/Hello.cpp
#include <iostream>
#include "shared/Hello.h"
void Hello::print()
{
std::cout << "Hello Shared Library!" << std::endl;
}
主程序文件放在currentDir/src目录下:
// src/main.cpp
#include "shared/Hello.h"
int main(int argc, char *argv[])
{
Hello hi;
hi.print();
// while (1)
// {
// /* code */
// }
return 0;
}
CMakeLists.txt放在currentDir目录之下:
cmake_minimum_required(VERSION 3.5)
project(hello_library)
############################################################
# Create a library
############################################################
#Generate the shared library from the library sources
add_library(hello_library SHARED
src/Hello.cpp
)
add_library(hello::library ALIAS hello_library)
target_include_directories(hello_library
PUBLIC
${PROJECT_SOURCE_DIR}/include
)
############################################################
# Create an executable
############################################################
# Add an executable with the above sources
add_executable(hello_binary
src/main.cpp
)
# link the new hello_library target with the hello_binary target
target_link_libraries( hello_binary
PRIVATE
hello::library
)
二、执行
- 新建目录build于currentDir之下。
- 在currentDir中打开终端
- 输入 cmake …
- 输入 cmake --build . --config release,此时生成动态库和可执行测试文件于Release中。
- 输入 .\Release\hello_binary.exe ,执行文件,输出 Hello Shared Library!
三、补充说明:
- 关键在于添加 __declspec(dllexport) 语句。
- 如要生成debug版本,第4步改为cmake --build . --config debug即可。
- 如果要生成静态库,将cMakeLists中
add_library(hello_library SHARED
src/Hello.cpp
)
中的SHARED 改为 STATIC 即可。