1、最簡單格式,即只有一個主cpp文件。
文件目錄
demo
|__build
|__src
| |__main.cpp
|__CMakeLists.txt
CMakeLists.txt文件
cmake_minimum_required(VERSION 2.8) # CMake最低版本要求,低於2.6的構建過程會被終止
project( HelloWorld ) # 定義工程名稱
add_executable( Hello src/main.cpp ) # 生成一個叫 Hello的可執行文件,其中可執行源文件路徑爲 src/main.cpp
main.cpp文件
#include <iostream>
using namespace std;
int main()
{
cout << "hello world!" << endl;
return 0;
}
2、帶頭文件
文件目錄
demo
|__build
|__include
| |__hello.h
| |__my_sum.h
|_____src
| |__main.cpp
|__CMakeLists.txt
CMakeLists.txt文件
cmake_minimum_required(VERSION 2.8) # CMake最低版本要求,低於2.6的構建過程會被終止
project( HelloWorld ) # 定義工程名稱
include_directories( ${PROJECT_SOURCE_DIR}/include) # 頭文件路徑
add_executable( Hello src/main.cpp ) # 生成一個叫 Hello的可執行文件,其中可執行源文件路徑爲 src/main.cpp
注:如果有多個.cpp文件,可以add_executable( Hello src/hello_world src/main.cpp )
hello.h文件
#ifndef __HELLO__
#define __HELLO__
#include <iostream>
using namespace std;
void Hello_world()
{
cout << "Hello world" << endl;
}
#endif /*__HELLO__*/
my_sum.h文件
#ifndef __MYSUM__
#define __MYSUM__
#include <iostream>
using namespace std;
int my_sum(int a, int b)
{
return a+b;
}
#endif /*__MYSUM__*/
main.cpp文件
#include <iostream>
#include "hello.h"
#include "my_sum.h"
using namespace std;
int main()
{
Hello_world();
cout << my_sum(1,2) << endl;
return 0;
}
3、添加opencv庫
文件目錄
demo
|____data
| |__1.jpg
|_____src
| |__main.cpp
|__CmakeLists.txt
CMakeLists.txt文件
cmake_minimum_required(VERSION 2.8) # CMake最低版本要求,低於2.6的構建過程會被終止
# set(CMAKE_CXX_STANDARD 14) #opencv4以上加此句
project(DisplayImage) # 定義工程名稱
find_package( OpenCV REQUIRED ) # opencv包
add_executable( Display src/main.cpp ) # 生成一個叫 Hello的可執行文件,其中可執行源文件路徑爲 src/main.cpp
target_link_libraries( Display ${OpenCV_LIBS}) # 鏈接庫
這裏需要注意opencv4需要C++11支持,因此需要添加set(CMAKE_CXX_STANDARD 14)
main.cpp文件
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
Mat img = imread("../data/1.jpg", 1);
imshow("img", img);
waitKey(0);
return 0;
}
參考:https://blog.csdn.net/qq_33179208/article/details/53558744