C++ 包含 Guard 奇怪的行为?

C++ Include Guard Weird Behaviour?

我正在使用 Ubuntu.
开发我的 SDL 游戏项目 我创建了一个 header(声明)及其 cpp 文件(定义)。
有些事情开始困扰我,请说明一下。

什么有用,我有什么:

(所有3个文件都在同一个文件夹下)

movement.h:

#include <SDL2/SDL.h>
class Movement{ ...... };`

movement.cpp:

    #include <SDL2/SDL.h>
    #include "movement.h"
    // Every Definition

main.cpp:

    #include <SDL2/SDL.h>
    #include "movement.h"
    ...... // contents

编译:

$ g++ main.cpp movement.cpp movement.h -lSDL2 -lSDL2_image

什么不起作用(包含防护):

(我只改了movement.cpp,其他没变)

movement.cpp:

#include <SDL2/SDL.h>
#ifndef MOVEMENT_H
#define MOVEMENT_H
...... // contents
#endif

错误:编译器抱怨无法识别来自 movement.h
的任何内容 例如:

......
movement.cpp: At global scope:
movement.cpp:73:6: error: ‘Movement’ has not been declared
......

我的问题:

1) 为什么我的 include guard(在 movement.cpp 中)不起作用?
我认为它会包括 "movement.h"(当还没有时)。

*对 <SDL2/SDL.h> 使用 include guard 也不起作用(编译器给出 "not been declared" 错误)。代码如下所示:

#ifndef SDL2_SDL_H
#define SDL2_SDL_H
......
#endif

2) 为什么 <SDL2/SDL.h> 不需要 include guard?
显然有一个包含在 movement.h 中,另一个包含在 main.cpp 中。 不应该有 双重包含 错误吗?

movement.h:

#include <SDL2/SDL.h>
class Movement{ ...... };

Headers 可能包含在多个文件中。你应该使用 header 守卫,这个 header.

似乎没有了

1) Why my include guard ( in movement.cpp ) doesn't work ?

movement.cpp:

#include <SDL2/SDL.h>
#ifndef MOVEMENT_H
#define MOVEMENT_H

源文件永远不应 包含 到其他文件中,因此您不需要 include 保护。


Compile:

$ g++ main.cpp movement.cpp movement.h -lSDL2 -lSDL2_image
                            ^^^^^^^^^^

Header个文件不需要编译


2) Why <SDL2/SDL.h> doesn't need an include guard ?

SDL2/SDL.h 确实有一个包含守卫:

#ifndef SDL_h_
#define SDL_h_

Apparently there's one included in movement.h and another in main.cpp. Shouldn't there be a double inclusion error ?

没有。 header 守卫删除了后者的包含。这就是 header 守卫的目的。

P.S。 Header 守卫只有在 header 有定义时才需要。一个只有声明的 header 不需要守卫。然而,简单地在所有 header 中使用一个 header 守卫比试图找出哪些 header 不需要它们要容易得多。