Include struct from header

271 Views Asked by At

How can one include a struct defined in an external header file into another file? At first, I passed the struct by pointer, so I only needed a forward declaration. But now I want to pass by value and can't make it compile. The header lagerverwaltung.h does include the struct, so where is the problem?

file lagerverwaltung.h:

#ifndef LAGERVERWALTUNG_H
#define LAGERVERWALTUNG_H

struct etikettInfo{
    QString userName;
    QList<struct properties_content *> inhalte;
};

class Lagerverwaltung : public QMainWindow
{
    Q_OBJECT
    ... and so on
};
#endif // LAGERVERWALTUNG_H

file etikett1.h:

#ifndef ETIKETT1_H
#define ETIKETT1_H

#include "lagerverwaltung.h" // for struct etikettInfo
class Lagerverwaltung;
//struct etikettInfo;

namespace Ui {
class Etikett1;
}

class Etikett1 : public QMainWindow
{
    Q_OBJECT
public:
    explicit Etikett1(Lagerverwaltung *mainwindow,
                      etikettInfo etikettData,  // <- struct etikettInfo has not been declared
                      QWidget* parent = 0);
    ~Etikett1();

private:
    Ui::Etikett1 *ui;
    Lagerverwaltung *lgrvw;
    etikettInfo etikettData;   // <- struct etikettInfo does not name a type
};

#endif // ETIKETT1_H

If it matters: Both .h-files do have include guards.

Ok the error messages (see comments in code) are really quite descriptive but I don't know what I should do differently.

2

There are 2 best solutions below

0
On BEST ANSWER

As it stands the

struct etikettInfo{
    QString userName;
    QList<struct properties_content *> inhalte;
};

needs the proper includes for this to be a properly declared struct. So add

#include <QString>
#include <QList>

as well as declaration for properties_content.

0
On

Also I have been including etikett1.h inside of lagerverwaltung.h

There's your bug. You include etikett1.h in lagerverwaltung.h which includes etikett1.h which includes lagerverwaltung.h and so on. In other words, you have a circular dependency. Your include guards prevent the infinite inclusion, but also cause one of the headers to be included before the other. In this case, lagerverwaltung.h was included first and before defining anything - etikettInfo in particular - it includes etikett1.h... which depends on etikettInfo which wasn't defined yet.

If lagerverwaltung.h truly depends on etikett1.h and the only thing etikett1.h depends on in lagerverwaltung.h is etikettInfo and nothing in lagerverwaltung.h depends on etikettInfo then the simplest solution is to split the definition of etikettInfo into another header and include that in etikett1.h instead of lagerverwaltung.h.