参考文章:
引言
如果使用cmake生成器(可查看HiConan文章)
[requires]
poco/1.9.4
[generators]
cmake #使用cmake生成器
在cmake中,需要这样来修改代码
cmake_minimum_required(VERSION 2.8.12)
project(MD5Encrypter)
add_definitions("-std=c++11")
#添加conan
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup() #conan初始设置
add_executable(md5 md5.cpp)
target_link_libraries(md5 ${CONAN_LIBS}) #链接你使用conan安装的所有lib文件
这样做有以下缺点:
- 与原始的cmakelists.txt写法不同,因此我们无法从原始的cmake文件中无缝切换成conan,也无法无缝地切换回去
- 所有的target都会链接到conan安装的所有库
cmake_find_package生成器
conan提供cmake_find_package生成器,它使得我们能够使用find_package
的方式来查找包,从而保持和原来一样。
conanfile.py
如果你在项目中使用conanfile.py
管理依赖包,可以参照这个来使用cmake_find_package
只需一步,在conanfile.py中将生成器改为cmake_find_package
即可
from conans import ConanFile, CMake, tools
class LibConan(ConanFile):
...
requires = "zlib/1.2.11"
generators = "cmake_find_package" #指定生成器
def build(self):
cmake = CMake(self) # it will find the packages by using our auto-generated FindXXX.cmake files
cmake.configure()
cmake.build()
在cmake中,像当初使用find_package一样编写即可
cmake_minimum_required(VERSION 3.0)
project(helloworld)
add_executable(helloworld hello.c)
find_package(ZLIB)
# Global approach
if(ZLIB_FOUND)
include_directories(${ZLIB_INCLUDE_DIRS})
target_link_libraries (helloworld ${ZLIB_LIBRARIES})
endif()
# Modern CMake targets approach
if(TARGET ZLIB::ZLIB)
target_link_libraries(helloworld ZLIB::ZLIB)
endif()
2022/3/25注:虽然官网这么说,但很像cmake还是找不到,不知道为什么。我通过本文conanfile.txt>方法二
解决了此问题
conanfile.txt
如果你在项目中使用conanfile.txt
来管理依赖库,需要做的事情就比较多了。
方法一
- 修改
conanfile.txt
中的生成器 ``` [requires] zlib/1.2.11 …
[generators] cmake_find_package cmake_paths
2. 在`CMakeList.txt`中添加一句话
```cmake
cmake_minimum_required(VERSION 3.0)
project(helloworld)
include(${CMAKE_BINARY_DIR}/conan_paths.cmake)
add_executable(helloworld hello.c)
find_package(ZLIB)
# Global approach
if(ZLIB_FOUND)
include_directories(${ZLIB_INCLUDE_DIRS})
target_link_libraries (helloworld ${ZLIB_LIBRARIES})
endif()
# Modern CMake targets approach
if(TARGET ZLIB::ZLIB)
target_link_libraries(helloworld ZLIB::ZLIB)
endif()
方法二
在
conanfile.txt
中修改生成器[requires]
zlib/1.2.11
...
[generators]
cmake_find_package
添加find_package搜索路径
cmake_minimum_required(VERSION 3.0)
project(helloworld)
list(APPEND CMAKE_MODULE_PATH ${CMAKE_BINARY_DIR})
list(APPEND CMAKE_PREFIX_PATH ${CMAKE_BINARY_DIR})
add_executable(helloworld hello.c)
find_package(ZLIB)
# Global approach
if(ZLIB_FOUND)
include_directories(${ZLIB_INCLUDE_DIRS})
target_link_libraries (helloworld ${ZLIB_LIBRARIES})
endif()
# Modern CMake targets approach
if(TARGET ZLIB::ZLIB)
target_link_libraries(helloworld ZLIB::ZLIB)
endif()