A portable way to untie a typedef pointer?

This, unfortunately, is defined in some external library: cannot touch!

// library.h
typedef struct {
    long foo;
    char *bar;
   /* ... (long & complex stuff omitted) */
} *pointer_to_complex_struct_t;

Now Question : how to declare a variable ? complex_struct_t

  • Ideal solution, but not allowed! (cannot change external library):

    // library.h
      /* ... (long & complex stuff omitted) */
    } complex_struct_t, *pointer_to_complex_struct_t;
    
    
    // my.h
    extern complex_struct_t my_variable;
    
  • Intolerable Solution (gcc):

    // my.h
    extern typeof( * (type_placeholder)0 )  my_variable; // Thanks caf!
    
  • Other? It's better? Thank!

Bonus question: The same question for a function pointer (if there is any difference, I doubt it).


ADDED bonus: - , . ( "" ), , . , , , ( ). , ? copy-paste. , , .

///// library.h //////
// Signature has been simplified
typedef double (*ptr_to_callback_t)(long, int, char *);
// Too bad this is not provided: typedef double callback_t(long, int, char *);

///// my.h /////
// This avoids copy-paste but is not portable
typedef typeof( * (ptr_to_callback_t)0 ) callback_t;

extern callback_t callback_1;
extern callback_t callback_2;
extern callback_t callback_3;
// etc.

= , typeof

- , . , : , .

+3
4

, , C. ++ .

,

typedef struct {
 ///same  struct
} complex_struct_t;

, &complex_struct_t pointer_to_complex_struct_t, unnamed struct {//your members}; reinterpret_casting, ...

+2

, ""; , ,

typedef struct {...} *ptr_to_struct;

(, ) . , , ,

ptr_to_struct s = malloc(sizeof *s);

, -> ( s ., ).

, ; , . ,

typedef struct {...} *ptr_to_struct;
ptr_to_struct foo() {...}

; .

+1

. , . ( - ), script, makefile , . , , (} *pointer_to_complex_struct_t;) , .

, include, . , , .

EDIT ( , ): . typedef, .

0

:

pointer_to_complex_struct_t newStruct ( void ) {
    pointer_to_complex_struct_t ptr = 
         (pointer_to_complex_struct_t) malloc ( sizeof (*pointer_to_complex_struct_t) );
    return ptr;
}

ptr- > , .

, , , . , , : ,

char data[0];

, .

0

Source: https://habr.com/ru/post/1773879/


All Articles