mcudm001
mcudm001

Reputation: 99

vector of structs giving error "not declared in this scope"

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?

Upvotes: 0

Views: 3312

Answers (5)

Thomas Havlik
Thomas Havlik

Reputation: 1388

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 ;)

Upvotes: 0

AnT stands with Russia
AnT stands with Russia

Reputation: 320777

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.

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283921

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.

Upvotes: 4

K-ballo
K-ballo

Reputation: 81409

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.

Upvotes: 0

vsz
vsz

Reputation: 4893

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

Upvotes: 1

Related Questions