Qt struct type redefinition/redefinition header

If you a new Qt programmer like me, may you ever get frustrated with this error

error: C2011: ‘sockaddr’ : ‘struct’ type redefinition

I got this error when I use the header WinSock2.h. There many people from http://stackoverflow.com suggest to include Winsock2.h before windows.h. So the code should be like this:

#include <Winsock2.h>
#include <windows.h>

May be this code is work for you, but if you are using mongodb c++ driver with Qt and must include multiple Winsock2.h in different header, you always get error “type redefinition”.
Qt error type redefinition
Still confused? Look this code:


#include <QDialog>

// MongoDB Connection
#ifdef Q_OS_WIN
    #include <WinSock2.h>
#endif // Q_OS_WIN
#include "mongo/client/dbclient.h" // for the driver

class FormLogin : public QDialog

    explicit FormLogin(QWidget* parent = 0);

#endif // FORMLOGIN_H

And the second header:

#ifndef TEACHERS_H
#define TEACHERS_H

#include <QtWidgets>

// MongoDB Connection
#ifdef Q_OS_WIN
    #include <WinSock2.h>
#endif // Q_OS_WIN
#include "mongo/client/dbclient.h" // for the driver

class Teachers : public TeachersModel

    Teachers(QWidget* parent = 0);

    mongo::DBClientConnection c;

#endif // TEACHERS_H

And if I run that code, Tadaaaaaaaa I got error like above picture. So how to fix the error?
That is very simple and I got the answer from this site http://stackoverflow.com/a/1517198/2425795. So open your Project.pro and add code _WINSOCAPI_:

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets



Note: just add the code highlighted.
And now right click your project and run qmake and rebuild your project.. Tadaaaaaaaa you not get an error again 😀
Source: http://stackoverflow.com/questions/1372480/c-redefinition-header-files


One comment

  1. Pretty section of content. I just stumbled upon your site
    and in accession capital to assert that I get in fact enjoyed account your blog posts.
    Any way I’ll be subscribing to your augment and
    even I achievement you access consistently rapidly.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s