redefinition c++

余生长醉 提交于 2019-12-04 04:03:50

问题


how does header including in c++ work? I have the classes already implemented in .h file and when there is #include in two files, there's this error:

files.h:14:7: error: redefinition of ‘class abstract_file’
files.h:14:20: error: previous definition of ‘class abstract_file’`

multiple times for each class and enum. Can anyone explain this?


回答1:


You can only include a definition one time but headers can be included multiple times. To fix that, add:

#pragma once

to the top of each header file.

While #pragma once is relatively common, if you are using an older compiler it may not be supported. In that case, you need to fall back on manual include guards:

#ifndef MY_HEADER_H
#define MY_HEADER_H

...

#endif

(note that you need to replace MY_HEADER_H with a unique string for each header file)




回答2:


Using include in C++ simply takes the file included and splats the contents into where it is included. To do this without worrying about multiple includes of the same file, you want to use header guards. Use this basic format for all header files:

#ifndef FILENAME_H
#define FILENAME_H

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

#endif



回答3:


header files usually define a unique symbol so that they are only included once.

e.g.

#ifndef _myheader_h
#define _myheader_h

// rest of header goes here

#endif

Some compilers support

#pragma once

See Pragma Once on wikipedia.




回答4:


While many people have solved your error for you, it seems that nobody has answered your initial question:

how does header including in c++ work?

When the preprocessor finds an #include directive it replaces it by the entire content of the specified file.

You can read more on preprocessor directives at cplusplus.com.

Update: To illustrate this, you could try the following if you have gcc handy:

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

You'll see the contrents of iostream whizz past your eyes as the preprocessed source code is sent to standard output.




回答5:


What you can do is to guard your header from multiple inclusions:

#ifndef MY_HEADER__
#define MY_HEADER__

/* your stuff goes here! */

#endif

You can also use:

#pragma once

but it is not standard although it is supported by many compilers.




回答6:


Use include guards in header files:

#ifndef FILES_H
#define FILES_H

struct foo {
    int member;
};

#endif // FILES_H

This makes sure that your header will only get included once.

Another method is to use #pragma once in your header files, but it's not standard C. It's supported by Visual C, GCC and Clang though, so most likely it's ok to use.



来源:https://stackoverflow.com/questions/2823330/redefinition-c

标签