I am learning how to do socket programming, and I tried to recreate the functionality of a c program: https://beej.us/guide/bgnet/examples/showip.c
In c++
(because I prefer c++ and its the language I intend to implement with) and it uses the headers:
stdio.h
string.h
sys/types.h
sys/socket.h
netdb.h
arpa/inet.h
netinet/in.h
I replaced stdio.h
with iostream
and string.h
with cstring
in my code.
I essentially typed line by line the code in his program, reading docs as I went to try and understand each function and struct. I know that in c++ it is not required (as in c) to precede instances of a struct with the struct
keyword, so anywhere there was a reference to a struct in his code I just omitted it.
In compilation, all of the structs in netinet/in.h were undefined! After some time of troubleshooting and various errors, I just downloaded his program source and made sure it wasn't an issue with my standard library (Cygwin is iffy?) Worked like a charm, but I still wanted c++.
I changed all stdio
stuff to iostream
and compiled it with g++
instead of gcc
and it still worked! The only thing that was different was having struct
in front of addrinfo and the other structs.
Is it required to place struct
in front of a struct instance in c++ when you use c header files?
Even if you use all the C
stuff (headers) in your program, at the end of the day it is recognized as a C++
source by your system if the file ends with .cpp
extension. So, if you don't need to put struct in front of every struct
instance as long as your source file is a C++
source file, it shouldn't show any compilation error.
That implies NO as the answer to your question.
Edit: As @JesperJuhl pointed out, this is not always true. Exceptions happen on AiX, VMS, Novell NetWare, DOS system. In that case, you'll need to use struct
keyword before every instance.
"Is it required to place "struct" in front of a struct instance in c++" - In general; No, That's a C'ism. Exceptions do exist though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With