2017-08-15 34 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