[GCC] Any tag of gcc to compile Cpp file which includes the 3rd party C header file

Ian Lance Taylor iant@google.com
Sat Apr 2 04:54:00 GMT 2011


Liao-Yuan Zhang <zhang.lyuan@gmail.com> writes:

> GCC experts, I encounter a problem here need your help:
> There is 3rd part header file (header.h) define a structure a below,
> it can be passed compiling when treat it as C language. But we trying
> to include this file in CPP file, and the compiling is failed since
> g++ compiling more restriction or other reason.
>
> shell@hercules$ g++ main.cpp
> In file included from main.cpp:1:
> header.h:10: error: conflicting declaration ‘typedef struct conn_t conn_t’
> header.h:9: error: ‘struct conn_t’ has a previous declaration as ‘struct conn_t’
> main.cpp: In function ‘int main()’:
> main.cpp:8: error: aggregate ‘conn_t list’ has incomplete type and
> cannot be defined
>
> Header file header.h:
>
>  1  #ifndef __HEADER_H__
>  2  #define __HEADER_H__
>  3  #ifdef __cplusplus
>  4  extern "C" {
>  5  #endif
>  6  typedef struct
>  7  {
>  8      int data;
>  9      struct conn_t *next;
> 10  }conn_t;
> 11
> 12  #ifdef __cplusplus
> 13  }
> 14  #endif
> 15
> 16  #endif // __HEADER_H__
>
> Cpp file main.cpp
>
>  1  #include "header.h"
>  2  #include <iostream>
>  3
>  4  using namespace std;
>  5  int main()
>  6  {
>  7      conn_t list;
>  8      list.data = 1;
>  9      list.next = NULL;
> 10      cout<<"hello:"<<list.data<<endl;
> 11      return 0;
> 12  }
>
> Question: Is there any tag of gcc/g++ to compile it?
> First, the header file is 3rd party C header file, it can be compiled
> in C language;
> Second, the header file can not be updated, just for specific purpose,
> I have to includes this header file in my C++ file, and then during
> compile the C++, the header file also will be treat as C++, that's
> what problem I encountered.

The header file is not written in valid C++.  There is no option which
will make it compile as C++.  It's valid C, but in C it doesn't mean
what you may think it means.  The field "next" does not point to to a
value of type "conn_t".  It points to a value of type "struct conn_t",
an entirely different type.  In C, "conn_t" and "struct conn_t" can be
different types.  In C++, they can not.  That is why this is an error in
C++.

If you can't change the header file, then I think your only option is to
#include it in a C file, write a C interface which does whatever you
need, and call that interface from your C++ code.

Ian



More information about the Gcc-help mailing list