用Cmake写Makefile

来源:互联网 发布:好看的域名 编辑:程序博客网 时间:2024/06/14 01:09

开始学Linux, 说实话还真的很痛苦

在Linux中写好一个c++程序, 需要两个过程才能形成一个可执行文件: compile和link

Compile是编译过程, 也就是把源文件生成一些中间目标文件.obj

Link是将这些.obj文件和library file中的.lib文件链接起来,并且生成可执行文件 .a


一般可以自己写makefile文件, 来预设上述过程所需的前提, 一般模式是

target: dependencies

[tab] system command

比较复杂容易出错


用Cmake来自动生成Makefile文件的一般步骤是

 - 写CMakeLists.txt文件

 - 在terminal中切换到源程序所在directory

- mkdir build

- cd build

- cmake ..

- make

- 在bin或者当前directory中运行./out.a

- 如果重新运行, 保险方法 rm -mf build 重新来一遍


重点是如何写CMakeLists.txt文件,下面是一个含OpenCV的一个Imread的例子, 源程序是imread.cpp

cmake_minimum_required (VERSION 2.8)project(Imread) find_package(OpenCV REQUIRED)add_executable(Imread imread.cpp)target_link_libraries(Imread ${OpenCV_LIBS})

再比如一个含有OpenCV和Curl两个library的

#version requirementcmake_minimum_required (VERSION 2.8)#project nameproject(Demo)#find linking librariesfind_package(OpenCV REQUIRED)find_package(CURL)IF (CURL_FOUND)MESSAGE(STATUS "Curl libraries found at: ${CURL_LIBRARIES}")MESSAGE(STATUS "curl includes found at ${CURL_INCLUDE_DIRS}")else()MESSAGE(SEND_ERROR "Could not find cURL on your system")ENDIF(CURL_FOUND)#find all source files in recent directory, ex main.cpp xx.hpp, x.cpp etcaux_source_directory(. DIR_SRCS)INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_SOURCE_DIR}/include )link_directories( ${CMAKE_BINARY_DIR}/bin )set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin)#generate executeable fileadd_executable (Demo ${DIR_SRCS})#add link libtarget_link_libraries(Demo ${OpenCV_LIBS} ${CURL_LIBRARIES})




0 0