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?


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



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


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!) {



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


#ifndef _myheader_h
#define _myheader_h

// rest of header goes here


Some compilers support

#pragma once

See Pragma Once on wikipedia.


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

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.


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

#ifndef MY_HEADER__
#define MY_HEADER__

/* your stuff goes here! */


You can also use:

#pragma once

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


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.