作为cmake初学者,在windows系统下使用cmake生成c++动态库时出现了下图所示问题,是关于lib文件。找了一圈,也没发现生成有lib文件。
在google上查,才发现windows系统下动态库生成lib文件,还需要添加以下命令:
#windows系统动态库生成lib文件命令
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
生成动态库Demo(链接在此)
- 文件目录架构:
——源文件目录
——hello-world.cpp
——CMakeLists.txt
——message
——|——Message.cpp
——|——CMakeLists.txt
——|——include
————|——Message.hpp
库源码文件在message目录,其中新建了文件夹include放置头文件Message.hpp。
库文件的CMakeLists.txt:
# set minimum cmake version
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
# project name and language
project(recipe-03 LANGUAGES CXX)
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
#配置编译后的输出路径
# 设定动态链接库的存储路径
SET(LIBRARY_OUTPUT_PATH ${CMAKE_CURRENT_LIST_DIR}/../bin)
include_directories(./include)
# generate a library from sources
add_library(message
SHARED
Message.cpp
)
Message库源代码:
Message.hpp
#pragma once
#include <iosfwd>
#include <string>
class Message {
public:
Message(const std::string &m) : message_(m) {}
friend std::ostream &operator<<(std::ostream &os, Message &obj) {
return obj.printObject(os);
}
private:
std::string message_;
std::ostream &printObject(std::ostream &os);
};
Message.cpp
#include "Message.hpp"
#include <iostream>
#include <string>
std::ostream &Message::printObject(std::ostream &os) {
os << "This is my very nice message: " << std::endl;
os << message_;
return os;
}
主CMakeLists.txt
# set minimum cmake version
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
# project name and language
project(recipe-03 LANGUAGES CXX)
#配置编译后的输出路径
# 设定动态链接库的存储路径
SET(LIBRARY_OUTPUT_PATH ${CMAKE_CURRENT_LIST_DIR}/../bin)
include_directories(./include)
# generate a library from sources
add_library(message
SHARED
Message.cpp
)
include_directories(./include)
main.cpp
#include "Message.hpp"
#include <iostream>
#include <string>
std::ostream &Message::printObject(std::ostream &os) {
os << "This is my very nice message: " << std::endl;
os << message_;
return os;
}
cmd命令进入到主MakeLists.txt所在目录后(需要提前下载Cmake及MinGW-w64,并将其bin路径添加到系统环境变量Path中):
cmake .
cmake --build .
最后在bin/debug会生成动态库的lib、dll文件,以及exe可执行文件。