1、目录结构:
/base
/main
main.cpp
CMakeLists.txt
/test1
test.h
2、文件内容:
2.1、不加头文件保护:多次包含重定义问题
#include "test.h"
#include "test.h"
int main()
{
func();
return 0;
}
include_directories(${CMAKE_SOURCE_DIR}/test1)
#include <iostream>
void func()
{
std::cout << "in file test1/test.h" << std::endl;
}
error: redefinition of 'void func()'
2.1、加头文件保护:不存在问题
#include "test.h"
#include "test.h"
int main()
{
func();
return 0;
}
include_directories(${CMAKE_SOURCE_DIR}/test1)
#ifndef TEST1_TEST
#define TEST1_TEST
#include <iostream>
void func()
{
std::cout << "in file test1/test.h" << std::endl;
}
#endif
in file test1/test.h
总结:
1、实际工作中肯定会出现头文件多级嵌套包含的场景,不可避免的存在同一头文件多次包含问题,因此必须对每一个头文件加宏定义保护。
2、加入头文件保护后,cpp文件在导入.h文件时,只会导入一次,第二次直接略过,因此不存在问题。
参考资料:
1、如果C源文件包含两个同名的头文件,将会发生什么?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)