C++ redefinition due to including header files multiple times

10,139

Solution 1

In your project settings: Project properties -> configuration -> advanced -> show includes.

It will dump the header include tree, from there you'll be able to see the culprit.

Solution 2

You need some or all of these before you include stdafx or windows.

#define _MSWSOCK_
#define NCB_INCLUDED
#define _WINSOCK2API_
#define _WINSOCKAPI_   /* Prevent inclusion of winsock.h in windows.h */

Solution 3

try replacing

#include <winsock2.h>

with

#ifndef _WINSOCK2API_
#include <winsock2.h>
#endif

Since _WINSOCK2API_ is defined inside winsock2.h, compiler will not try to include it multiple times.

Solution 4

I had the same problem recently and solved it including winsock2.h before including windows.h.

Share:
10,139
akif
Author by

akif

Updated on June 04, 2022

Comments

  • akif
    akif almost 2 years

    As, the title says. I'm encountering redefinition errors due to including header files multiple times. I know its because of that, but I don't know how to resolve. Yes, I previously posted the same problem in SO an hour ahead. But I wasn't able to explain properly (I think so) and didn't get answers expected. Here is the link:

    C++ Redefinition Header Files

    I'm not editing that question since it has been filled up :).

    Okay I have some classes and the structure of them is like this:

    main.cpp:

    #include "Server.h"
    #include "Handler.h"
    #include "Processor.h"
    
    int main(int argc, char* argv[])
    {
    
    }
    

    Server.h:

    // Server.h
    #pragma once
    
    #include <winsock2.h>
    

    Handler.h:

    // Handler.h
    #pragma once
    
    #include <string>
    #include <vector>
    
    #include "Server.h"
    

    Processor.cpp:

    // Processor.cpp
    
    #include "StdAfx.h"
    #include "Processor.h"
    #include "Handler.h"
    

    Server.cpp:

    // Server.cpp
    
    #include "Server.h"
    #include "Processor.h"
    

    The problem is that <winsock2.h> is included multiple times, don't know where but it is. #pragma once serves the same purpose as

    #ifndef SOME_FILE_H
    #define SOME_FILE_H
    // code here
    #endif // SOME_FILE_H
    

    in my compiler (MSVC2008 in this case). So I'm pretty much sure I don't need the header include guards. But can you spot where I'm doing the mistake by which <winsock2.> is included twice and how may I resolve?

    Thanks