C ++ Override

How does the header contained in C ++ work? I have classes already implemented in the .h file, and when there are #includetwo files, there is this error:

files.h:14:7: error: redefinition ofclass abstract_file
files.h:14:20: error: previous definition ofclass abstract_file’`

several times for each class and listing. Can anyone explain this?

+3
source share
6 answers

You can only include a definition once, but headers can be included multiple times. To fix this, add:

#pragma once

at the top of each header file.

Although #pragma oncerelatively common, if you are using an old compiler, it may not be supported. In this case, you need to return to manually turning on the guards:

#ifndef MY_HEADER_H
#define MY_HEADER_H

...

#endif

( , MY_HEADER_H )

+6

include ++, , . , , . :

#ifndef FILENAME_H
#define FILENAME_H

class foo (or whatever else is in the file!) {
    ...
};

#endif
+6

, .

.

#ifndef _myheader_h
#define _myheader_h

// rest of header goes here

#endif

#pragma once

Pragma Once .

+2

, , :

, ++?

#include, .

cplusplus.com.

. , , gcc:

echo '#include <iostream>' > test.cxx 
gcc -E test.cxx

, , .

+2

, :

#ifndef MY_HEADER__
#define MY_HEADER__

/* your stuff goes here! */

#endif

:

#pragma once

, .

0
source

Use include guard in header files:

#ifndef FILES_H
#define FILES_H

struct foo {
    int member;
};

#endif // FILES_H

This ensures that your title will be included only once.

Another method is to use #pragma onceheaders in your files, but it is not standard C. It is supported by Visual C, GCC, and Clang, although this is most likely normal to use.

0
source

All Articles