目录结构:
hello.h
#ifndef HELLO_H
#define HELLO_H
#include <iostream>
void hello();
#endif
hello.cpp
#include "hello.h"
void hello(){
std::cout << "Hello " << std::endl;
}
world.h
#ifndef WORLD_H
#define WORLD_H
#include <iostream>
void world();
#endif
world.cpp
#include "world.h"
void world() {
std::cout << "world\n" << std::endl;
}
main.cpp
#include "hello/hello.h"
#include "world/world.h"
int main(int argc, char *argv[])
{
hello();
world();
return 0;
}
注意这里的头文件,引入相对路径,否则会报找不到该头文件。
如果不想这样添加头文件,可以用这个方式 CMake系列之四:多个源文件-多个目录
接下来我也会介绍这种方式。
CMakeLists.txt
# CMake 最低版本号要求
cmake_minimum_required(VERSION 3.5)
# 设置工程名
project (hello_cmake)
aux_source_directory(${PROJECT_SOURCE_DIR} DIR_MAIN_SRCS)
aux_source_directory(${PROJECT_SOURCE_DIR}/hello DIR_HELLO_SRCS)
aux_source_directory(${PROJECT_SOURCE_DIR}/world DIR_WORLD_SRCS)
# 指定生成目标
add_executable(hello_cmake ${DIR_MAIN_SRCS} ${DIR_HELLO_SRCS} ${DIR_WORLD_SRCS})
接着就是输入命令:
cd build
cmake ..
make
运行结果: