2017-08-15 85 views
0

我需要社区的帮助,编译错误是关于使用g++编译的C嵌套结构。C++嵌套结构的g ++编译错误

我有以下三个文件:

main.cpp中(的完整性;该文件不需要重现编译错误):

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

int main(int argc, char* argv[]) 
{ 
    someFunc(); 
    return 0; 
} 

ns.h

#ifndef NS_H 
#define NS_H 

#ifdef __cplusplus 
extern "C" { 
#endif 

void someFunc(); 

#ifdef __cplusplus 
} 
#endif 

#endif // NS_H 

ns.c

#include "ns.h" 

#ifdef __cplusplus 
extern "C" { 
#endif 

#define MY_MAX (42) 

typedef struct _outer 
{ 
    int count; 
    struct Inner 
    { 
    int count; 
    void* cb; 
    void* ctx [ MY_MAX ]; 
    } inner_[ MY_MAX ]; 
} Outer; 

Outer g_outer[ 10 ]; 

#include "staticFuncs.h" 

void someFunc() 
{ 
    staticFunc(); 
} 

#ifdef __cplusplus 
} 
#endif 

staticFuncs.h

#include <stdio.h> 

#ifdef __cplusplus 
extern "C" { 
#endif 

static void anotherStaticFunc() 
{ 
    printf("%s", __FUNCTION__); 

    struct Inner* ptr = NULL; 
    ptr = &(g_outer[ 0 ].inner_[ 0 ]); 
    (void)ptr; 
} 

static void staticFunc() 
{ 
    printf("%s", __FUNCTION__); 
    anotherStaticFunc(); 
} 

#ifdef __cplusplus 
} 
#endif 

相关编译如下:

>g++ --version 
g++ (GCC) 4.8.3 20140911 (Red Hat 4.8.3-7) 
Copyright (C) 2013 Free Software Foundation, Inc. 
This is free software; see the source for copying conditions. There is NO 
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 


>g++ -g -c ns.c -o ns.o 
In file included from ns.c:22:0: 
staticFuncs.h: In function 'void anotherStaticFunc()': 
staticFuncs.h:12:7: error: cannot convert '_outer::Inner*' to 'anotherStaticFunc()::Inner*' in assignment 
    ptr = &(g_outer[ 0 ].inner_[ 0 ]); 
    ^

是怎么回事?

我知道在C中,嵌套的结构体没有被任何范围的语法引用,但被称为,虽然它们没有嵌套。也就是说,我很有信心,我可以像staticFuncs.h那样做struct Inner* ptr = NULL;。比我的自信更重要的是,如果我用cc而不是g++进行编译,编译就会完成。

我已经尽我damnedest告诉g++说我在extern "C"到处都是扔编译C,不C++,代码,但它仍然绊倒的Inner作用域。

任何人都可以请帮助找出为什么这个编译器错误出现,我该如何解决呢?我必须使用g++进行编译。

的问题是,如果没有改变是staticFuncs.h代替staticFuncs.c

如果静态函数不是静态的,则问题不变。如果staticFuncs.h/c内容被嵌入在ns.c而不是被#include

的问题是保持不变。

+0

»我已经尽我damnedest告诉克+ +我正在编译C,而不是C++«你为什么那么即使试图用C++编译器?只需使用'gcc'而不是'g ++'。 –

+0

这是在工作中我没有选择编译器的问题的简化。 – StoneThrow

+3

'extern“C”'对语言没有影响,它只影响如何生成符号。 – molbdnilo

回答

1

虽然gcc会将代码编译为C++,如果它具有某些后缀,那么无法用g ++编译C。
gcc和g ++的唯一区别在于后者总是编译C++,并且它与C++库链接。

最简单的解决方法是

struct Inner 
{ 
    int count; 
    void* cb; 
    void* ctx [ MY_MAX ]; 
}; 

typedef struct _outer 
{ 
    int count; 
    struct Inner inner_[ MY_MAX ]; 
} Outer; 
+0

这工作;谢谢。我想我在'gcc'和'g ++'之间混合了'C' /'C++'双重能力。 – StoneThrow

1

来自编译器的错误消息非常明确。

赋值运算符的LHS被声明为:

struct Inner* ptr = NULL; 

这相当于行:

// Declare a struct in the function. This is different from _outer::Inner. 
struct Inner; 

// Declare the variable using the struct declared in the function. 
struct Inner* ptr = NULL; 

你需要做的是使用_outer::Inner*作为ptr类型。

_outer::Inner* ptr = NULL; 
+0

不,请注意,正如我在后文中所描述的那样,我正在运行'g ++'来编译'C'代码。 '_outer :: Inner'风格是'C++'语法。这段代码需要用'C'和'C++'编译器编译。 – StoneThrow