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

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

image.png

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

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

解决

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

一、使用dllexport将外部需要使用到的类导出
  1. #ifndef __HELLO_H__
  2. #define __HELLO_H__
  3. #ifdef HELLO_EXPORT
  4. #define EXPORT __declspec(dllexport)
  5. #else
  6. #define EXPORT
  7. #endif
  8. class EXPORT Hello
  9. {
  10. public:
  11. void print();
  12. };
  13. #endif

二、更改CMakeList.txt文件,为cmake_examples_inst库添加HELLO_EXPORT
  1. cmake_minimum_required(VERSION 3.5)
  2. project(cmake_examples_install)
  3. ############################################################
  4. # Create a library
  5. ############################################################
  6. #Generate the shared library from the library sources
  7. add_library(cmake_examples_inst SHARED
  8. src/Hello.cpp
  9. )
  10. target_include_directories(cmake_examples_inst
  11. PUBLIC
  12. ${PROJECT_SOURCE_DIR}/include
  13. )
  14. # 为cmake_examples_inst库添加宏HELLO_EXPORT,以便它能生成.lib文件(Windows中,dllexport之后才会生成.lib文件)
  15. target_compile_definitions(cmake_examples_inst PRIVATE HELLO_EXPORT)
  16. ############################################################
  17. # Create an executable
  18. ############################################################
  19. # Add an executable with the above sources
  20. add_executable(cmake_examples_inst_bin
  21. src/main.cpp
  22. )
  23. # link the new hello_library target with the hello_binary target
  24. target_link_libraries( cmake_examples_inst_bin
  25. PRIVATE
  26. cmake_examples_inst
  27. )
  28. ############################################################
  29. # Install
  30. ############################################################
  31. # Binaries
  32. install (TARGETS cmake_examples_inst_bin
  33. DESTINATION bin)
  34. # Library
  35. # Note: may not work on windows
  36. install (TARGETS cmake_examples_inst
  37. LIBRARY DESTINATION lib)
  38. # Header files
  39. install(DIRECTORY ${PROJECT_SOURCE_DIR}/include/
  40. DESTINATION include)
  41. # Config
  42. install (FILES cmake-examples.conf
  43. DESTINATION etc)

结果

image.png