目录架构如下:
--|HelloWordTest
-------------------|demo
---------------------------|cmd-dir.cpp
---------------------------|hello-world.cpp
-------------------|inc
---------------------------|test.h
-------------------|src
---------------------------|test.cpp
-------------------|output
-------------------|CMakeLists.txt
cmd-dir.cpp:
#include <cstdlib>
#include <iostream>
#include <string>
#include "test.h"//包含test.h头文件
int main(int argc,char** argv)
{
std::cout<<"this is cmd_dir"<<std::endl;
test_log();//调用test中的函数
return EXIT_SUCCESS;
}
hello-world.cpp:
#include <cstdlib>
#include <iostream>
#include <string>
std::string say_hello()
{
return std::string("hello word!");
}
int main(int argc,char** argv)
{
std::cout<<say_hello()<<std::endl;
return EXIT_SUCCESS;
}
test.h:
//inc/test.h
#ifndef TEST_H
#define TEST_H
int test_log();
#endif
test.cpp:
// src/test.cpp
#include <iostream>
#include "test.h"
int test_log()
{
std::cout<<"This is test_log"<<std::endl;
return 0;
}
CmakeList.txt:
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)//指定cmake最低版本3.5
project(hello-world-01 LANGUAGES CXX)//指定项目名称hello-world-01 使用语言是C++
SET(CMAKE_CXX_COMPILER /usr/bin/g++)//指定使用g++作为编译器,否则在MSYS2中会出现std:cout未定义
include_directories(${PROJECT_SOURCE_DIR}/inc)//添加头文件目录
SET(src_dir ${PROJECT_SOURCE_DIR}/src)//包含src源文件目录
file(GLOB src_codes ${src_dir}/*.cpp)//遍历保存源代码文件
SET(demo_dir ${PROJECT_SOURCE_DIR}/demo)//定义demo_dir指向demo子文件夹
file(GLOB demo_codes ${demo_dir}/*.cpp)//定义demo_codes执行demo子文件中的所有.cpp源文件
foreach(demo ${demo_codes})//遍历.cpp源文件
string(REGEX MATCH "[^/]+$" demo_file ${demo})//通过正则表达式获取文件名并保存到demo_file
string(REPLACE ".cpp" "" demo_basename ${demo_file})//去除.cpp后缀名并保存到demo_basename
add_executable(${demo_basename} ${demo} ${src_codes})//将每一个源文件生成为单独一个可执行的程序
endforeach()
cd进入output文件夹,依次执行命令
cmake..//在当前目录的上层目录中查找CMakeLists.txt,并在当前目录中构建工程
make