Reputation: 6431
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?
Upvotes: 3
Views: 6475
Reputation: 141998
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.
Upvotes: 2
Reputation: 4522
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.
Upvotes: 0
Reputation: 57787
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.
Upvotes: 2
Reputation: 96939
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.
Upvotes: 0
Reputation: 9866
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
Upvotes: 7
Reputation: 76611
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)
Upvotes: 6