#pragma once 与包含守卫

Vin*_*nod 4 c++ pragma include-guards

我正在经历实现定义的行为控制

并且有以下与 相关的文字#pragma once

与头文件保护不同的是,这个 pragma 使得不可能在多个文件中错误地使用相同的宏名称。

我不确定这意味着什么。有人可以解释一下吗?

TIA

eer*_*ika 8

例子:

// src/featureA/thingy.h
#ifndef HEADER_GUARD_FOR_THINGY
#define HEADER_GUARD_FOR_THINGY
struct foo{};
#endif


// src/featureB/thingy.h
#ifndef HEADER_GUARD_FOR_THINGY
#define HEADER_GUARD_FOR_THINGY
struct bar{};
#endif


// src/file.cpp
#include "featureA/thingy.h"
#include "featureB/thingy.h" // oops, this file is removed by header guard
foo f;
bar b;
Run Code Online (Sandbox Code Playgroud)

标题保护宏需要一丝不苟的努力来保持它们的独特性。#pragma once自动做到这一点。

公平起见,为了完整性,让我提一下缺点(也在链接页面中):#pragma once如果从多个路径中包含同一个文件,则无法识别它。对于具有奇异文件结构的项目,这可能是一个问题。例子:

// /usr/include/lib.h
#pragma once
struct foo{};


// src/ext/lib.h
#pragma once
struct foo{};


// src/headerA.h
#pragma once
#include <lib.h>

// src/headerB.h
#pragma once
#include "ext/lib.h"

// src/file.cpp
#include "headerA.h"
#include "headerB.h" // oops, lib.h is include twice
foo f;
Run Code Online (Sandbox Code Playgroud)