Some languages are forgiving. The programmer needs only a basic sense of how things work. Errors in the code are flagged by the compile-time or run-time system, and the programmer can muddle through and eventually fix things up to work correctly. The C language is not like that.
C is a small yet incredibly powerful language. Created by Dennis Ritchie at Bell Labs in the early 1970s, it was the language that took operating systems programming by storm, and, soon after, general-purpose software development as well. It’s also one of the most dangerous languages out there. C is infamous for being unforgiving to novice programmers because of its minimal yet versatile syntax that can be easily misused if not well understood. Nevertheless, the C ecosystem offers an immense treasury of tools and libraries at your fingertips.
Although Fortran programmers have been writing mixed Fortran and C applications for several decades, the interoperability features were officially introduced into the standard in Fortran 2003, and further improved in later revisions (2008 and 2018). In practice, interfacing C functions with data structures from Fortran boils down to correctly writing the interfaces, which means matching the data types of function arguments. This chapter will teach you very little C. After all, this a book about Fortran programming, and C is a whole other beast. If you have some experience with C, great! Otherwise, don’t worry. I’ll gently guide you through interfacing with C code from Fortran, and you’ll learn all you need to know to do so, without having to learn C on the side. If you want to learn more about C, near the end of the chapter I provide references that I like.
To get your feet wet with interfacing with C from Fortran, we’ll develop a minimal TCP client and server. We’ll start with an existing C library that’s easy to download and install and is well documented. One step at a time, we’ll write Fortran interfaces with C functions that we’ll use. With only several function calls, we’ll have a working TCP server running as a Fortran program and listening for incoming connections from anywhere in the world. We’ll wrap up the chapter by writing a small TCP client, so in the end we’ll have two Fortran programs talking to each other over the network.
Transmission Control Protocol (TCP) is one of the most widely used protocols that power the internet. It allows reliable, error-checked transfer of binary data between hosts (computers) connected on an IP (Internet Protocol) network. TCP is a base transport layer for several different application layers, such as HTTP (Hypertext Transfer Protocol), commonly used to deliver content to web browsers, or websockets, used for responsive real-time networking, such as chat clients or collaborative office tools.