开发者

Any tag of gcc to compile Cpp file which includes C 3rd party header file

开发者 https://www.devze.com 2023-02-21 13:57 出处:网络
There is 3rd part he开发者_开发知识库ader 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 co

There is 3rd part he开发者_开发知识库ader 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

#include "header.h"
#include <iostream>

using namespace std;
int main()
{
    conn_t list;
    list.data = 1;
    list.next = NULL;
    cout<<"hello:"<<list.data<<endl;
    return 0;
}

Question: Is there any tag of gcc/g++ to compile it?


typedef struct
{
   int data;
   struct conn_t *next;
}conn_t;

I don't know if in some compilers what you're doing here is valid, but it seems wrong to me. If you use a typedef you shouldn't prefix the typename with struct. Also the name conn_t in this case will be defined as soon as the struct is declared but isn't valid inside the declaration. This way the code'll work:

struct conn_t
{
   int data;
   struct conn_t *next;
};

No typedefs, I'm just using the struct name.


It should be written like this in order to have a typedef and to have a reference to the structure itself:

typedef struct tag_conn_t
{
   int data;
   struct tag_conn_t *next;
}conn_t;

Good luck,

Iulian


  1. First, the header file is 3rd party C header file, it can be compiled in C language;
  2. 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.

I still need you genius give me the answer for that, really appreciate your guys response here.


I believe the -x language tag, with c-header for language on gcc/g++ is what you are looking for.

0

精彩评论

暂无评论...
验证码 换一张
取 消