[CMake] 示例 多模块与安装(01-basic_E-installing Windows环境下,无法打开*.lib)

该示例地址:https://github.com/ttroy50/cmake-examples.git
学cmake看这个仓库就可以了

【问题】在Windows环境下,编译01-basic_E-installing时,提示找不到lib文件

[CMake] 示例 多模块与安装(01-basic_E-installing Windows环境下,无法打开*.lib)

【原因】在Windows中,需要为导出类或函数设置dllexport之后,才会生成lib文件。

  1. 用官方给的例子。编译之后,你会发现,没有cmake_examples_inst.lib文件

解决

修改两个文件,其他文件不变

一、使用dllexport将外部需要使用到的类导出
#ifndef __HELLO_H__
#define __HELLO_H__

#ifdef HELLO_EXPORT
#define EXPORT __declspec(dllexport)
#else
#define EXPORT 
#endif

class EXPORT Hello
{
public:
    void print();
};

#endif
二、更改CMakeList.txt文件,为cmake_examples_inst库添加HELLO_EXPORT
cmake_minimum_required(VERSION 3.5)

project(cmake_examples_install)

############################################################
# Create a library
############################################################

#Generate the shared library from the library sources
add_library(cmake_examples_inst SHARED
    src/Hello.cpp
)

target_include_directories(cmake_examples_inst
    PUBLIC 
        ${PROJECT_SOURCE_DIR}/include
)
# 为cmake_examples_inst库添加宏HELLO_EXPORT,以便它能生成.lib文件(Windows中,dllexport之后才会生成.lib文件)
target_compile_definitions(cmake_examples_inst PRIVATE HELLO_EXPORT)

############################################################
# Create an executable
############################################################

# Add an executable with the above sources
add_executable(cmake_examples_inst_bin
    src/main.cpp
)

# link the new hello_library target with the hello_binary target
target_link_libraries( cmake_examples_inst_bin
    PRIVATE 
        cmake_examples_inst
)

############################################################
# Install
############################################################

# Binaries
install (TARGETS cmake_examples_inst_bin
    DESTINATION bin)

# Library
# Note: may not work on windows
install (TARGETS cmake_examples_inst
    LIBRARY DESTINATION lib)

# Header files
install(DIRECTORY ${PROJECT_SOURCE_DIR}/include/ 
    DESTINATION include)

# Config
install (FILES cmake-examples.conf
    DESTINATION etc)

结果

[CMake] 示例 多模块与安装(01-basic_E-installing Windows环境下,无法打开*.lib)

上一篇:LeetCode 213 打家劫舍II


下一篇:rabbitmq中的三种交换器(匹配模式)