当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - how to handle cpp files and header files

问题描述:

I have a bit of a problem with header's and cpp files,

I started creating a little text based game and i wanted to make all the work more clearer by creating more files and separated files to each class (Player.cpp, Monster.cpp Entity etc..).

So I ended up with a lot of #include directive's in each cpp file (i haven't used headers yet).

I needed a the rand function so i added stdlib to each class, and iostream to player class and etc..

so i ended up with a lot of double and triple uses of the same library, what should i do to avoid it?

is there any way to avoid it at all?

(creating a separate class for random for example wont work because i need to add it to the classes as well any ways).

Thanks in advance!

EDIT:

But if i have something like this?:

main.cpp -> Player.h -> stdlib.h

 -> Monster.h -> stdlib.h

what can i do to make stdlib.h to be in all classes without warning or errors?

In other words, how can i create header's without including a lot of the same library in each with? (Player and Monster are different classes and they both need stdlib, what should i do to include just once that library?)

网友答案:

What do you mean with "I haven't used headers yet"? You must create headers for you function declarations / class definitions. There is no other reasonable way.
Next you need to read about include guards. Include guards ensure that a header is not included more than once, directly and indirectly.
In almost all modern compilers you can use #pragma once instead of the old #if !defined... style.

网友答案:

This may not be the best way but this is the way I do it I always have a main.cpp file which called a 'MasterHeader.h' file and inside that header file I have all the other headers, so in the main I only have one line which calls all my other headers and that header sorts out what headers I need.

So

main.cpp > MasterHeader.h > myHeader.h, myOtherHeader.h, thisHeader.h

Etc

网友答案:

Correct me if i get this wrong... Your facing errors of redefinition due to including your own cpp files at multiple points.

One way would be to create a header for the code files you need to include elsewhere and declare your exports in this header. Ensure that the exports are defined once per created object by using the preprocessor

// some_file.h
#ifndef SOME_FILE_H
#define SOME_FILE_H
...
//export declarations
...
#endif

or you avoid including your code files and declare the functions you need as 'extern'

//your_functions.cpp
int some_function( int arg1 )
{
    ...
}

and

//other_file.cpp
extern int some_function( int );
分享给朋友:
您可能感兴趣的文章:
随机阅读: