一、包含头文件的工程,目录结构:
Hello.h内容:
#ifndef __HELLO_H__ #define __HELLO_H__ class Hello { public: void print(); }; #endif
Hello.cpp内容:
#include <iostream> #include "Hello.h" void Hello::print() { std::cout << "Hello Headers!" << std::endl; }
main.cpp内容:
#include "Hello.h" int main(int argc, char *argv[]) { Hello hi; hi.print(); return 0; }
二、CMakeLists.txt内容:
# Set the minimum version of CMake that can be used # To find the cmake version run # $ cmake --version cmake_minimum_required(VERSION 3.5) # Set the project name project (hello_headers) # Create a sources variable with a link to all cpp files to compile set(SOURCES src/Hello.cpp src/main.cpp ) # Add an executable with the above sources add_executable(hello_headers ${SOURCES}) # Set the directories that should be included in the build command for this target # when running g++ these will be included as -I/directory/path/ target_include_directories(hello_headers PRIVATE ${PROJECT_SOURCE_DIR}/include )
1、cmake中set表示定义变量,上述中变量SOURCES的值为:src/Hello.cpp、src/main.cpp
2、${SOURCES}表示使用变量,在cmake使用变量的值必须使用${变量名}
3、target_include_directories():指定最终生成目标文件所包含的头文件搜素路径 参考链接:https://www.ravenxrz.ink/archives/e40194d1.html
这是因为每个 target 都有两个用来装 include dir 的变量,分别叫做 INCLUDE_DIRECTORIES 和 INTERFACE_INCLUDE_DIRECTORIES。 前者用于存放专给自己用的 INCLUDE DIR, 后者则用于存放暴露给外部程序的 INCLUDE DIR。你可以把他想象成两个放食物的篮子,INCLUDE_DIRECTORIES 篮子放的东西给自己吃,INTERFACE_INCLUDE_DIRECTORIES 篮子放的东西给别人吃。
PUBLIC|PRIVATE|INTERFACE 就是在指定将定义的 INCLUDE DIR 放置到哪个篮子,或者两个都放。
PUBLIC: 将 include dir 放到两个篮子中,自己用,也给别人用。
PRIVATE: 将 include dir 只放到自己的篮子中。
INTERFACE: 将 include dir 只放到别人的篮子中。
三、执行流程
1、可以看到每个.o是单独生成的,
2、可以看到,每个.o生成都会去这个路径下面搜索 -I/root/cmake-examples-master/cmake-examples-master/01-basic/B-hello-headers/include
0.0分
1 人评分