有第三部分头文件(header.h)定义了下面的结构体a,当它作为C语言处理时可以通过编译。但是我们试图将这个文件包含在CPP文件中,并且编译失败,因为g ++编译更多限制或其他原因?gcc的任何标签可以编译包含C第三方头文件的Cpp文件
[email protected]$ 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.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文件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;
}
问:是否有编译它的GCC/G ++任何标记?
这里有C和C++之间的另一个区别。在C++中,不需要'typedef struct conn_t conn_t;'来使用不带'struct'的conn_t名称。它无论如何工作。 – 2011-04-01 06:53:08
感谢您的回答,但由于头文件是第三方,所以不会更新头文件。 – 2011-04-01 09:02:40
是的,定义是有效的C,但在C中,字段“next”不指向类型为“conn_t”的值,它指向类型“struct conn_t”的值,这是一个完全不同的类型。在C中,“conn_t”和“struct conn_t”可以是不同的类型。在C++中,他们不能。这就是为什么这是C++中的错误。但是在这里,我们必须将“conn_t”和“struct conn_t”视为同一类型。 – 2011-04-03 03:31:59