C ++ Header Files - Confused!

game.h needs:
- packet.h
- socket.h

server.h needs:
- socket.h

socket.h needs:
- game.h

The problem occurs when I try to include socket.h in game.h, because socket.h already has game.h. How to solve these problems?

+5
source share
6 answers

The usual way to use #ifdef and #define in your header files

inside game.h:

#ifndef GAME_H
#define GAME_H

.. rest of your header file here

#endif

Thus, the content will be read several times, but will be determined only once.

Change . The underscore at the beginning and end of the identifier for comments has been removed.

+17
source

- . game.h, socket.h ( ), , . game_forwards.h. :

// game_fwd.h

#ifndef GAME_FWD_H
#define GAME_FWD_H

class game;

#endif // ndef GAME_FWD_H

// game.h

#ifndef GAME_H
#define GAME_H

#include "socket.h"

class game {
    socket* m_sck;
};

#endif // ndef GAME_H

// socket.h

#ifndef SOCKET_H
#define SOCKET_H

#include "game_fwd.h"

class socket {
    game* m_game;
};

#endif // ndef SOCKET_H

, .

+9

( -) , - , . , , .

+8

:

#pragma once 

.

, , .

, , . Visual ++.

+3

, , - , - , . , game.h connect() socket.h, game.h:

void connect();

socket.h. , connect() , , . , , .

game.h socket.h, :

class Socket;

, -, . ++ FAQ Lite.

+1

@lassevk, it should not be "the header file will be opened several times, but the preprocessor will read the contents of the file between #ifndef and #endif once during the first read. After that, the preprocessor will ignore additional PP macros because _GAME_H has been defined."

0
source

All Articles