0

I have a struct declared as follows:

#ifndef PLAYLIST_H
#define PLAYLIST_H
#include <iostream>
#include <string>
#include <vector>
#include "playlistitem.h"
#include "song.h"
#include "time.h"
struct Playlist {
    std::vector<Song> songs;
    Time cdTotalTime;
    int totalTime;
};

and struct Song declared in another file:

#ifndef SONG_H
#define SONG_H
#include "playlist.h"
#include "time.h"
struct Song {
    std::string title;
    std::string artist;
    std::string album;
    int track;
    Time length;
};

I have both struct definitions in headers, and both are #included as they should be.

When I compile I get an error at

std:vector<Song> songs;

error 'Song' was not declared in this scope

What am I missing?

3
  • 4
    Are you sure you have included the Song's definition file in the file, defining Playlist ? And that it's in the same namespace? Commented Nov 4, 2011 at 20:48
  • 2
    How are you "including them as they should be"? (Hint: You're not ;) ) Commented Nov 4, 2011 at 20:49
  • Please show us the file where you use the definitions. Commented Nov 4, 2011 at 20:50

5 Answers 5

4

playlist.h includes song.h

song.h should NOT include playlist.h

Header guards prevent infinite recursion, they don't fix circular dependencies.

Currently song.h does include playlist.h. Then when playlist.h includes song.h, nothing happens (because of the header guard), and Song is not defined. So playlist.h produces errors.

Sign up to request clarification or add additional context in comments.

Comments

1

Not only your main file, but the file where Playlist is declared should also #include the file where Song is in.

Comments

0

The definition of Song has to come before its used in the definition of Playlist. Since they are in different headers, you should make sure that the header for Playlist includes that of Song, and both have proper header guards.

Comments

0

Your headers include each other in circular fashion. This is useless and unnecessary. Why is your song.h including playlist.h? Remove #include "playlist.h" from song.h and that should fix the error.

Comments

0

You could prototype Song in your header by putting struct Song; and just include the header in your .c/.cpp file. This has the bonus of faster compile times! :D

Recursive includes work fine with include guards, as long as you arrange them properly. I always try and include the least amount of headers in .h files, leaving them for the source files.

Also, I don't see a #endif on your code. Right now I'm assuming your code actually has it ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.