0

I have a C code that works in the following way: the header contains a declaration for the function, say:

typedef struct MyStruct
{
    int thing;
    void* reserved;
} MyStruct;

void foo(MyStruct* bar);

And then, in my .c code, I have this:

typedef struct EXTENDED
{
    float more_stuff;
} EXTENDED;

struct MyStructEx
{
    int thing;
    EXTENDED* ex;
} MyStructEx;

void foo(MyStructEx* bar)
{
    ...
}

This compiles fine under MSVC (with warnings telling me that the header and implementation parameters don't match) but Code::Blocks (GCC) throws an error on it. Is there a way to silence this error or at least make it a warning, or is my only option to put the extra definitions in the header as well?

I'm doing this because I'm coding a modular library in C, so sometimes the individual components require "scratch space" to work (which is the void* reserved in the header), and to avoid having a bunch of casts everywhere I'm trying to implicitly cast the general-purpose MyStruct structure to a more specialized one.

So my question is, which option should I use to change this sort of error into a warning, and/or is there a better way to achieve this? (I am required to use standard C).

4

2 に答える 2

3

関数プロトタイプを保持し、関数定義にポインターをキャストします

typedef struct EXTENDED
{
    float more_stuff;
} EXTENDED;

struct MyStructEx
{
    int thing;
    EXTENDED* ex;
} MyStructEx;

void foo(MyStruct* bar)
{
    MyStructEx *mse = (MyStructEx*)bar;
    ...
}

コンパイラをシャットダウンします。

于 2012-07-11T22:39:21.437 に答える
1

MyStruct*との間の暗黙的な変換はありませんMyStructEx*

(用語の問題: 「暗黙のキャスト」などというものはありません。キャストは、括弧で囲まれた型名で構成されるキャスト演算子を使用した明示的な変換です。)

void*EXTENDED*が同じサイズと表現を持つという保証もありません。たとえば、void*8 バイトとEXTENDED*4 バイトは完全に合法です。

同じレイアウトを想定MyStructMyStructExて使用する手法は、プログラムの動作を未定義にします。

fooaを取るMyStruct*関数とneedをfoo取るMyStructEx*関数は、2つの異なる名前を持つ2つの異なる関数である必要があるようです。それらの 1 つは、もう 1 つのラッパーになることができます。

それか、必要な変換を行って、MyStructExタイプをドロップMyStructしてすべてに使用することができます。foo()

于 2012-07-11T22:44:40.827 に答える