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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With