Utiliser un typedef pour le prototypage de fonctions
J'ai un souci sur l'emploi des typedef, qui seront utilisés dans des prototypes de fonctions (j'ai résolut le problème en attendant dans le prototype la partie ' struct nom' plutôt que le type definit, c'est plus par curiosité, pour confirmation et en prévision de la reproduction du problème dans un projet plus grand que j ouvre ce thread).
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| #ifndef BAR_H
#define BAR_H
#include <stdio.h>
#include <stdlib.h>
#include "foo.h"
typedef struct t_bar{
int i;
int j;
}bar;
void bar_funct(bar *p_bar, foo* p_foo);
#endif |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| #ifndef FOO_H
#define FOO_H
#include <stdio.h>
#include <stdlib.h>
#include "bar.h"
typedef struct t_foo{
int i;
int j;
}foo;
void foo_funct(foo *p_foo, bar* p_bar);
#endif |
gcc foo.c bar.c main.c
In file included from foo.h:7:0,
from foo.c:1:
bar.h:16:27: error: expected declaration specifiers or '...' before 'foo'
In file included from bar.h:7:0,
from bar.c:1:
foo.h:16:28: error: expected declaration specifiers or '...' before 'bar'
In file included from foo.h:7:0,
from main.c:4:
bar.h:16:27: error: expected declaration specifiers or '...' before 'foo'
Cela signifie que typedef ne definit pas completement le type ?
Je met alors le type complet dans chaque declaration de fonction (et leurs definition dans les fichiers c)
Pour bar.h
Code:
void bar_funct(bar *p_bar, struct t_foo* p_foo);
Pour foo.h
Code:
void foo_funct(foo *p_foo, struct t_bar* p_bar);
J'ai maintenant des warnings
In file included from foo.h:7:0,
from foo.c:1:
bar.h:16:35: warning: 'struct t_foo' declared inside parameter list
bar.h:16:35: warning: its scope is only this definition or declaration, which is
probably not what you want
In file included from bar.h:7:0,
from bar.c:1:
foo.h:15:35: warning: 'struct t_bar' declared inside parameter list
foo.h:15:35: warning: its scope is only this definition or declaration, which is
probably not what you want
In file included from foo.h:7:0,
from main.c:4:
bar.h:16:35: warning: 'struct t_foo' declared inside parameter list
bar.h:16:35: warning: its scope is only this definition or declaration, which is
probably not what you want
Je vais donc définir chaque structure dans chaque fichiers qui l'utilise
foo.h
Code:
1 2 3 4 5 6 7 8
| #include "bar.h"
struct t_bar;
typedef struct t_foo{
int i;
int j;
}foo; |
bar.h
Code:
1 2 3 4 5 6 7 8
| #include "foo.h"
struct t_foo;
typedef struct t_bar{
int i;
int j;
}bar; |
Et la plus de warnings,
Questions :
*est ce la bonne facon de faire ?
*peut on mettre des typedef dans le prototype d'une fonction comme dans le premier exemple ? Ou faut il prévoir des le debut de l'écriture des headers l'emploi du type complet avec le struct en toute lettre ?
*N'y a t'il pas un mot cle extern qui peut être utilisé ici pour ce problème ? (je ne me rappel son usage exacte)