工程目錄結構如下:
manyFolderCompile3:工程的根目錄。
bin:會生成的可執行文件的目錄,需要把圖片放到這個目錄。在沒有改動“main.cpp”文件中的讀取圖片的名字情況下,圖片的名字只能是“123.jpeg”。
build:會進入這個目錄執行編譯命令。
include:存放頭文件的目錄。
lib:生成鏈接庫的目錄。
src:存放源文件的目錄
相應文件的內容如下:
CMakeLists.txt
cmake_minimum_required (VERSION 2.8)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra")
set(CUDA_TOOLKIT_ROOT_DIR /usr/local/cuda)
project (testCmake)
add_definitions(-std=c++11)
find_package(OpenCV REQUIRED)
set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/bin)
aux_source_directory(. ALL_SRCS) # 添加當前目錄下所有的源文件
add_subdirectory(src) # 添加math子目錄
add_executable(testCmake ${ALL_SRCS}) # 指定生成目標,注意這裏要用${ALL_SRCS}!!!
target_link_libraries(testCmake power) # 添加鏈接庫,power是在math子目錄的CMakeLists中定義的
target_link_libraries(testCmake ${OpenCV_LIBRARIES})
power.h
#ifndef POWER_H
#define POWER_H
double power(double base, int exponent);
#endif
main.cpp
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include<opencv2/opencv.hpp>
#include "include/power.h" //特別注意自己定義的函數頭文件需要用引號括起來
using namespace std;
using namespace cv;
int main(int argc, char *argv[])
{
if (argc < 3){
printf("Usage: %s base exponent \n", argv[0]);
return 1;
}
double base = atof(argv[1]);
int exponent = atoi(argv[2]);
double result = power(base, exponent);
cout << base << ' ' << '^' << ' ' << exponent << ' ' << "is" << ' ' << result << endl;
cout << "yes" << endl;
Mat srcImage=imread("123.jpeg");
imshow("Origin",srcImage);
waitKey(0);
return 0;
}
src/CMakeLists.txt
include_directories(
${PROJECT_SOURCE_DIR}/include
)
aux_source_directory(. LIB_SRCS) # 添加當前目錄下所有的源文件
add_library (power ${LIB_SRCS}) # 當前目錄下的文件生成一個鏈接庫
power.cpp
#include "power.h" //特別注意自己定義的函數頭文件需要用引號括起來
double power(double base, int exponent)
{
int result = base;
int i;
if (exponent == 0) {
return 1;
}
for(i = 1; i < exponent; ++i){
result = result * base;
}
return result;
}
在創建完該工程後,進入build目錄,執行如下命令:
cmake ..
make
cd ..
cd bin
./testCmake 2 2
其結果如下: