Reputation: 47
I am currently programming a program which searches song according to diffrent parameters. In my system there are 2 types of songs: lyric and instrumetal. Since i need to put both of them in 1 vector, I have a song class and a LyricsSong & InstrumentalSong subclasses.
So I there is a Song.h file:
#include <stdio.h>
#include <iostream>
#include <string>
class Song
{
public:
std::string title;
virtual void print();
virtual void printSong(std::string query);
};
and there are the instrumental and lyrics subclasses, which are defined this way:
class LyricsSong : public Song
class InstrumentalSong : public Song
both of the include Song.h, and in both of them the class is defines only in the header file.
when I try to run another file which use the both subclasses, and includes:
#include "LyricsSong.h"
#include "InstrumentalSong.h"
(and obviously more cpp libraries), i get the following compilation error:
In file included from /cygdrive/c/Users/Username/Documents/C++ Workshop/ex2/ex2_code/InstrumentalSong.h:16:0,
from /cygdrive/c/Users/Username/Documents/C++ Workshop/ex2/ex2_code/songsParser.cpp:26:
/cygdrive/c/Users/Username/Documents/C++ Workshop/ex2/ex2_code/Song.h:6:7: error: redefinition of 'class Song'
class Song
^
In file included from /cygdrive/c/Users/Username/Documents/C++ Workshop/ex2/ex2_code/LyricsSong.h:15:0,
from /cygdrive/c/Users/Username/Documents/C++ Workshop/ex2/ex2_code/songsParser.cpp:25:
/cygdrive/c/Users/Username/Documents/C++ Workshop/ex2/ex2_code/Song.h:6:7: error: previous definition of 'class Song'
class Song
^
when:
What should I do? P.S. I do not import any cpp file ever, only header files.
Upvotes: 2
Views: 8937
Reputation: 111
As already answered, I would also use #pragma once, it is more convenient and clean. But be aware that it is not a C++ standard, so it can be a problem if you have to use different compilers (although it is a wide-spread extension).
Upvotes: 1
Reputation: 1092
You have to tell preprocessor to include your header files only once. You can achieve by adding #pragma once
on the top of all *.h
files:
#pragma once
//Your header file's code
It is also a good practice to always begin header files with this line.
Upvotes: 13
Reputation: 2376
They both include 'Song.h' file and preprocessor takes the file content twice. You need to write 'LyricsSong.h' and 'InstrumentalSong.h' file contents inside #ifndef #define and #endif directives. Like this
#ifndef LYRICS_SONG_H
#define LYRICS_SONG_H
your code goes here.
...
#endif
Upvotes: 5