Search code examples
c++extern

Including C header file containing standard includes (without C++11)


I already looked at the following two posts on the same topic: Post1 Post2. I have a similar problem but not the same (I guess). So posting it here. Sorry if it is still a duplicate.

I have a C-static library(libComm.a) which contains the implementation for the following ..

comm.h:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <math.h>
.....
typedef struct _CDef {} CommDef;

And I get this file delivered. I cannot change it in anyway. Apart from this I also have another Cpp library (libfw.a):

fw.h:

namespace fw { namespace ipc {
class A { ...... };
} }

My aim is to use both the libraries in my C++ application:

myCppApp.cpp

#include "fw.h"
extern "C" {
#include "comm.h"
}

namespace chat { namespace comm {
class CppApplication
{
private:
   CommDef def;
   fw::ipc::A ipc;
};
}
}

When I want to compile this, the compiler cannot find, "fw::ipc::A". But if I do not use the C header and the corresponding data type, everything works fine.

I realized this is because the header file I am including contains standard C include files. So, my question is how can I solve this compile issue and at the end link successfully to the lib, with the following conditions:

  1. Without changing the delivered sources
  2. Without using C++11 to include the corresponding CPP definitions because of point-1

Many thanks for your time.


Solution

  • The problem is that the C header is polluting the preprocessor with #defines. One possibility is to clean up afterwards using #undef:

    extern "C" {
    #include "comm.h"
    }
    #undef ipc
    // ...
    

    The other option is to add aliases for names that the C header makes inaccessible, before including it:

    #include "fw.h"
    typedef fw::ipc::A fw_ipc_A;
    extern "C" {
    #include "comm.h"
    }
    // ...
    fw_ipc_A ipc_;