I am working with pcap code and the struct udphdr seems to be defined in two includes. How to tell GCC to use a specific one?
-
2What happens when you include both headers? Does the compiler give an error message? Please post the message. Are the struct udphdr a variable definition, or just a struct type declaration? Do you know if they headers are otherwise different? Do you know which header *must* be included? – gbulmer Mar 21 '12 at 02:02
-
There is no compiler error. One definition is like this http://www.linuxbase.org/navigator/browse/type_single.php?cmd=display&id=37079 and the other like this http://tomoyo.sourceforge.jp/cgi-bin/lxr/source/include/linux/udp.h. The compiler seems to only recognize the latter but I believe the first is the correct one. – dmz73 Mar 21 '12 at 02:59
4 Answers
If you want to uh_* elements , you must use -D_BSD_SOURCE macro as parameter of gcc, despite you get the following errors:
error: ‘struct udphdr’ has no member named ‘uh_sport’
error: ‘struct udphdr’ has no member named ‘uh_dport’
error: ‘struct udphdr’ has no member named ‘uh_ulen’
error: ‘struct udphdr’ has no member named ‘uh_sum’
error: ‘struct udphdr’ has no member named ‘uh_sum’

- 2,845
- 6
- 47
- 67
Upon looking at /usr/include/netinet/udp.h more carefully the problem is not that the same struct is defined in two different headers. In this file it is defined as:
/* UDP header as specified by RFC 768, August 1980. */
#ifdef __FAVOR_BSD
struct udphdr {
u_int16_t uh_sport; /* source port */
u_int16_t uh_dport; /* destination port */
u_int16_t uh_ulen; /* udp length */
u_int16_t uh_sum; /* udp checksum */
};
#else
struct udphdr {
u_int16_t source;
u_int16_t dest;
u_int16_t len;
u_int16_t check;
};
#endif
So it looks like it is using the POSIX version of the struct which I believe is ok.

- 9,339
- 6
- 34
- 51

- 1,588
- 4
- 20
- 32
I can't see a simple way to deal with that. I've done a few tests with #undef
without success.
I would re-declare the struct
you are interested in somewhere else in your own code, under a different name to avoid clashing, and then use it in the code with this new name.
This approach has problems, of course: what happens if the original header get's updated and that structure changes (some new members, others get removed), you know what I mean?

- 92,053
- 36
- 243
- 426
Just use the right one: netinet/udp.h
under Linux:
From Linux Standard Base:
http://www.linuxbase.org/navigator/browse/type_single.php?cmd=display&id=37079

- 142,963
- 15
- 272
- 331