#include <iostream>int main(int argc, char argv){ std::cout << "this is a simple example!" << "\n"; return 0;}
cmake_minimum_required(VERSION 3.16)project(CMakeSunny VERSION 1.0 DESCRIPTION "A CMake Tutorial" LANGUAGES CXX)add_executable(cmlearn main.cpp)
mkdir buildcd buildcmake ..make
cmake_minimum_required(VERSION 3.16)project(CMakeSunny VERSION 1.0 DESCRIPTION "A CMake Tutorial" LANGUAGES CXX)add_executable(add main.cpp add.cpp)
int add(int a, int b){ return a+b;}
int add(int a, int b);
#include <iostream>#include "add.h"int main(int argc, char argv){ int r = add(1, 3); std::cout << "this is a simple example!" << r << "\n"; return 0;}
完成上述修改后,大家可以切回到build目录中,重新执行cmake ..和make命令,可以看到生成了新的二进制文件cmlearn我们可以执行一下这个程序,可以看到结果符合预期包含子目录的软件工程实际的大型项目比上面介绍的还要复杂的多比如上文我们提到实现了一个加法功能的add.cpp文件比如我们又要实现减法、乘法和除法等功能,也都是在独立的文件中实现那么这些计算的实现最好放到一个目录中,比如math目录在大型项目中经常会这样组织源代码,一个功能模块的代码,或者详细功能的代码被组织在一个子目录中这是源代码会被组织成如下图所示的结构,而且在子目录math中也需要新建一个名称为CMakeLists.txt文件该文件的内容可以非常简单,具体如下所示,是不是很简单add_library(math OBJECT sub.cpp add.cpp)
add_library(<name> [STATIC | SHARED | MODULE] [EXCLUDE_FROM_ALL] [<source>...])add_library(<name> OBJECT [<source>...])add_library(<name> INTERFACE)add_library(<name> <type> IMPORTED [GLOBAL])
add_subdirectory(math)
target_link_libraries(cmlearn PUBLIC math)
target_include_directories(cmlearn PUBLIC "${PROJECT_SOURCE_DIR}/math")
#include <iostream>#include "add.h"#include "sub.h"int main(int argc, char argv){ int sum = add(1, 3); int diff = sub(3, 1); std::cout << "The sum of 1 and 3 is " << sum << std::endl; std::cout << "The diff of 3 and 1 is " << diff << std::endl; return 0;}
(图片来源网络,侵删)
0 评论